繁体   English   中英

Python Elementtree通过属性值访问子级

[英]Python Elementtree access children through attribute value

如何访问带有属性值“ 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>

我已经尝试了多种变体,但是我不知道如何做。

这是一种方法:

>>> 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表示法访问您感兴趣的元素。此外, child.attrib是一个字典。 您可以作为child.attrib['x']等访问x, y and z的值,依此类推

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM