Python Elementtree通过属性值访问子级

时间:2014-08-26 18:59:52

标签: python elementtree

如何使用属性值“test5”访问标记,然后使用python和elementtree访问其子项“loc”和子项“rot”。

在此之后,我想将元素loc x,y,z的每个值存储在一个单独的变量中。

    <item name="test1">
        <loc x="0" y="0" z="0"/>
        <rot x="1" y="0" z="0" radian="0"/>
    </item>
    <item name="test2">
        <loc x="22" y="78.7464" z="109.131"/>
        <rot x="-1" y="0" z="0" radian="1.35263"/>
    </item>
    <item name="test3">
        <loc x="-28" y="-106.911" z="71.0443"/>
        <rot x="0" y="0.779884" z="-0.625923" radian="3.14159"/>
    </item>
    <item name="test4">
        <loc x="38" y="51.6772" z="94.9353"/>
        <rot x="1" y="0" z="0" radian="0.218166"/>
    </item>
    <item name="test5">
        <loc x="-38" y="-86.9568" z="64.2009"/>
        <rot x="0" y="-0.108867" z="0.994056" radian="3.14159"/>
    </item>

我尝试了多种变体,但我不知道如何做到这一点。

1 个答案:

答案 0 :(得分:2)

这是一种方法:

>>> import xml.etree.ElementTree as ET
>>> data = '''<root>
... <item name="test1">
...     <loc x="0" y="0" z="0"/>
...     <rot x="1" y="0" z="0" radian="0"/>
... </item>
... <item name="test2">
...     <loc x="22" y="78.7464" z="109.131"/>
...     <rot x="-1" y="0" z="0" radian="1.35263"/>
... </item>
... <item name="test3">
...     <loc x="-28" y="-106.911" z="71.0443"/>
...     <rot x="0" y="0.779884" z="-0.625923" radian="3.14159"/>
... </item>
... <item name="test4">
...     <loc x="38" y="51.6772" z="94.9353"/>
...     <rot x="1" y="0" z="0" radian="0.218166"/>
... </item>
... <item name="test5">
...     <loc x="-38" y="-86.9568" z="64.2009"/>
...     <rot x="0" y="-0.108867" z="0.994056" radian="3.14159"/>
... </item>
... </root>'''

>>> tree = ET.fromstring(data)
>>> for child in tree.findall("./item[@name='test5']/"):
...     print child.tag, child.attrib
...

这给出了:

loc {'y': '-86.9568', 'x': '-38', 'z': '64.2009'}
rot {'y': '-0.108867', 'x': '0', 'z': '0.994056', 'radian': '3.14159'}

它使用XPath notation来访问您感兴趣的元素。此外,child.attrib是一个字典。您可以将x, y and z的值设为child.attrib['x'],依此类推

相关问题