Python Elementtree通过属性值访问子级
如何使用python和elementtree访问属性值为“test5”的标记,然后访问其子级“loc”和子级“rot” 在此之后,我想将元素locx,y,z的每个值存储在一个单独的变量中Python Elementtree通过属性值访问子级,python,elementtree,Python,Elementtree,如何使用python和elementtree访问属性值为“test5”的标记,然后访问其子级“loc”和子级“rot” 在此之后,我想将元素locx,y,z的每个值存储在一个单独的变量中 <item name="test1"> <loc x="0" y="0" z="0"/> <rot x="1" y="0" z="0" radian="0"/> </item> <item name="
<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
...
它使用访问您感兴趣的元素。此外,
child.attrib
是一本字典。您可以访问x、y和z的值作为child.attrib['x']
等等。发布一些您尝试过的代码。我如何访问test5的loc的y值?抱歉,我对python非常陌生。@NilsOrbat就像我上面说的,你会做一个child.attrib['y']
loc {'y': '-86.9568', 'x': '-38', 'z': '64.2009'}
rot {'y': '-0.108867', 'x': '0', 'z': '0.994056', 'radian': '3.14159'}