Как извлечь значение атрибута из xml, используя python - PullRequest
0 голосов
/ 14 марта 2020

Как мне получить доступ к Car из подэлемента коробки. Я могу получить имя атрибута, но сталкиваюсь с проблемой, чтобы получить Car

<annotations>
      <image height="940" id="0" name="90.jpg" width="1820">
        <box label="Objects" occluded="1" xbr="255" xtl="0" ybr="624" ytl="509">
         <attribute name="Class">Car</attribute>
         <attribute name="Occlusion %">25-50%</attribute>
         <attribute name="Truncation %">0%</attribute>
        </box>
      </image>
    </annotations>

1 Ответ

1 голос
/ 14 марта 2020

см. Ниже

import xml.etree.ElementTree as ET


xml = '''<annotations>
      <image height="940" id="0" name="90.jpg" width="1820">
        <box label="Objects" occluded="1" xbr="255" xtl="0" ybr="624" ytl="509">
         <attribute name="Class">Car</attribute>
         <attribute name="Occlusion %">25-50%</attribute>
         <attribute name="Truncation %">0%</attribute>
        </box>
      </image>
    </annotations>'''

#
# Find the attribute element (under box element) where the attribute name value is 'Class'. print the text of the element text
#
root = ET.fromstring(xml)
print(root.find(".//box/attribute[@name='Class']").text)
...