Python Learning notes (21)

Source: Internet
Author: User

Parsing an XML file using ElementTree

# import the built-in Python module for processing XML files
Try
Import Xml.etree.cElementTree as ET
Except Importerror:
Import Xml.etree.ElementTree as ET

#准备XML字符串数据
Xml_data_str = "<?xml version=" 1.0 "encoding=" Utf-8 "?>
<!--comments--
< bookshelf >
< book publishing house = "Shanghai, China" >
< name > Sin </name >
< author > Sanding </author >
< price >32.00</price >
< publication date >2007 </publication date >
</book >
< book publishing house = "Beijing, China" >
< name > LOL </name >
< author > Jin Yong </author >
< price >50.00</price >
</book >
</Bookshelf > "'

# Prepare parsing XML string
if __name__ = = "__main__":
# Get the root node of XML
Xml_root = et.fromstring (XML_DATA_STR)
# Displays information about the output root node
Print ("=========== root node information ============")
Print ("Root node Name:", Xml_root.tag)
Print ("Root node Properties:", Xml_root.attrib)
Print ("Root node text:", Xml_root.text)
# Get book node information
Book_list = Xml_root.findall ("book")
For x in Book_list:
Print ("Name:", X.find ("First Name"). Text)
Print ("", X.find ("author"). Text)
Print ("Price:", X.find ("price"). Text)


Parsing results:

C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe d:/projects/pythonpro/python_01.py
=========== root node information ============
Root node Name: Bookshelf
Root node properties: {}
Root node text:

Name: Sin Xian
Sanding
Price: 32.00
Name: Proud of the lake
Jin yong 's
Price: 50.00

Process finished with exit code 0

Python Learning notes (21)

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.