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:
<MiddleCommand xsi:type="MoveToType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <CommandID>19828</CommandID> <MoveStraight>false</MoveStraight> <EndPosition> <Point> <X>528.65</X> <Y>33.8</Y> <Z>50.0</Z> </Point> <XAxis> <I>-0.7071067811865475</I> <J>-0.7071067811865477</J> <K>-0.0</K> </XAxis> <ZAxis> <I>0.0</I> <J>0.0</J> <K>-1.0</K> </ZAxis> </EndPosition> </MiddleCommand>
Python code:
import xml.etree.ElementTree as ET #tree = ET.parse("102122.955_prog_14748500480769929136.xml") tree = ET.parse("Move_to.xml") root = tree.getroot() for Point in root.findall("./EndPosition/Point/X"): print(Point.text) for Point in root.findall('.//{MoveToType}/Endposition/Point/X'): print(Point.text)
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.
import xml.etree.ElementTree as ET tree = ET.parse("Move_to.xml") # The real XML, with several MiddleCommand elements for MC in tree.findall(".//MiddleCommand"): # Check xsi:type value and if it equals MoveToType, find the X value if MC.get("{http://www.w3.org/2001/XMLSchema-instance}type") == 'MoveToType': X = MC.find(".//X") print(X.text)