orbatschow
orbatschow

Reputation: 1537

Python Elementtree access children through attribute value

How can I access the tag with the attribute value "test5" and then its child "loc" and the child "rot" with python and elementtree.

After this i want to store every value of the element loc x, y, z in a seperate variable.

    <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>

I have tried multiple variants, but i have no clue, how to do it.

Upvotes: 0

Views: 939

Answers (1)

shaktimaan
shaktimaan

Reputation: 12092

This is one way to do it:

>>> 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
...

This gives:

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

It uses the XPath notation to access the element you are interested in. Furthermore, child.attrib is a dictionary. You can access the values of x, y and z as child.attrib['x'] and so on

Upvotes: 2

Related Questions