Reference: https://docs.python.org/2/library/xml.etree.elementtree.html
Example:
<?XML version= "1.0"?><Data> <Countryname= "Liechtenstein"> <Rank>1</Rank> < Year>2008</ Year> <GDPPC>141100</GDPPC> <Neighborname= "Austria"direction= "E"/> <Neighborname= "Switzerland"direction= "W"/> </Country> <Countryname= "Singapore"> <Rank>4</Rank> < Year>2011</ Year> <GDPPC>59900</GDPPC> <Neighborname= "Malaysia"direction= "N"/> </Country> <Countryname= "Panama"> <Rank>68</Rank> < Year>2011</ Year> <GDPPC>13600</GDPPC> <Neighborname= "Costa Rica"direction= "W"/> <Neighborname= "Colombia"direction= "E"/> </Country></Data>
1. Parsing XML files
>>>OS.GETCWD ()'D:\\workspace\\testpython'>>>ImportXml.etree.ElementTree as ET>>> tree = Et.parse ('Test.xml')>>> root =tree.getroot ()>>>PrintRoot<element'Data'At 0x1d2a8b0>>>>PrintTree<xml.etree.elementtree.elementtree Object at 0x01d2a9d0>>>>Root.tag'Data'>>>root.attrib{}>>>#Traversing child nodes>>> forChildinchRoot:PrintChild.tag,child.attrib Country {'name':'Liechtenstein'}country {'name':'Singapore'}country {'name':'Panama'}>>>Root[0].text'\ n'>>> root[0][1].text' -'>>> root[1][3].text>>> root[1][2].text'59900'
2. Find elements
>>>#Querying elements>>> forNeighborinchRoot. ITER ('neighbor' ): PrintNeighbor.attrib {'direction':'E','name':'Austria'}{'direction':'W','name':'Switzerland'}{'direction':'N','name':'Malaysia'}{'direction':'W','name':'Costa Rica'}{'direction':'E','name':'Colombia'}>>> Root.iter ('Neighbor')<generator Object iter at 0x01d3cf30>>>>root.findall ('country' )[<element'Country'at 0x1d2aa90> <element'Country'at 0x1d2ad30> <element'Country'At 0x1d2af10>]>>> forCountryinchRoot.FindAll('Country'):#Element.findall () queries the child elements of the current elementRank=country.Find('Rank').text #Element.find () queries the first child element of the specified label, Element.text gets the contents of the elementName=country.Get('name')#Element.get () gets the attribute value of the element PrintName,rank Liechtenstein1Singapore4Panama68
3. Modify the XML file
Python processes XML files