I know there are a few similar questions but none of the solutions seemed to work. I need to parse and XML file using python. I am using Elementree I am trying to print the value X. It is working as long as I am just looking for X-Values within EndPosition but I have to look for within all MoveToType. Is there someway to integrate that in Elementree. Thanks!
XML file:
JavaScript
x
22
22
1
<MiddleCommand xsi:type="MoveToType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
2
<CommandID>19828</CommandID>
3
<MoveStraight>false</MoveStraight>
4
<EndPosition>
5
<Point>
6
<X>528.65</X>
7
<Y>33.8</Y>
8
<Z>50.0</Z>
9
</Point>
10
<XAxis>
11
<I>-0.7071067811865475</I>
12
<J>-0.7071067811865477</J>
13
<K>-0.0</K>
14
</XAxis>
15
<ZAxis>
16
<I>0.0</I>
17
<J>0.0</J>
18
<K>-1.0</K>
19
</ZAxis>
20
</EndPosition>
21
</MiddleCommand>
22
Python code:
JavaScript
1
16
16
1
import xml.etree.ElementTree as ET
2
3
4
#tree = ET.parse("102122.955_prog_14748500480769929136.xml")
5
tree = ET.parse("Move_to.xml")
6
root = tree.getroot()
7
8
9
for Point in root.findall("./EndPosition/Point/X"):
10
print(Point.text)
11
12
13
14
for Point in root.findall('.//{MoveToType}/Endposition/Point/X'):
15
print(Point.text)
16
Advertisement
Answer
Here is how you can get the wanted X
value for MiddleCommand
elements with xsi:type="MoveToType"
. Note that you need to use the full namespace URI inside curly braces when getting the value of the attribute.
JavaScript
1
10
10
1
import xml.etree.ElementTree as ET
2
3
tree = ET.parse("Move_to.xml") # The real XML, with several MiddleCommand elements
4
5
for MC in tree.findall(".//MiddleCommand"):
6
# Check xsi:type value and if it equals MoveToType, find the X value
7
if MC.get("{http://www.w3.org/2001/XMLSchema-instance}type") == 'MoveToType':
8
X = MC.find(".//X")
9
print(X.text)
10