如何使用 python 从 xml 中提取属性值
How to extract attribute value from xml using python
如何从 box 子元素访问 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>
见下文
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)
如何从 box 子元素访问 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>
见下文
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)