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)