[Python learning] using the Xml.etree.ElementTree module to process XML

Source: Internet
Author: User
Tags tag name

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.