---restore content starts---
Import data (read file and read string)
Local file country_data.xml
<?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>
Reading XML from a file
Import= et.parse ('country_data.xml'= Tree.getroot ()
Reading XML from a string
Root = et.fromstring (country_data_as_string)
Element.tag, Element.text and Element.attributes
# Root.tag Read tag name # Root.attrib Read Attributes # root[0][1].rank Reading text values print root.tag # output root node element <data> tag name: Dataprint root.attrib # output root node element <data> attributes (null value): {} print root[0][2].text # Output The text value of the first <country> sub-element <gdppc>: 141100
Element.iter ()
# root.iter (' neighbor ') find all descendant elements for in Root.iter ('neighbor'): Print neighbor.attrib
Find () and FindAll ()
# Find () returns the first child element print root.find ('country')# Fund () returns all child elements Print root.findall ('country')
Copy manual:
Https://docs.python.org/2/library/xml.etree.elementtree.html
[Python learning] using the Xml.etree.ElementTree module to process XML