Tag:xml serialization python
<diva_list> <diva name= "Hamasaki ayumi" > <state flop= "Yes" >1</state> <year>1978</year> <album_sales_volume> 27804358</album_sales_volume> <album name= "A song for xx " sn=" 1st "/> <album Name= "Loveppears" sn= "2nd"/> </diva> <diva name= "Koda kumi" > <state flop= "yes" >2 </state> <year>1982</year> <album_sales_volume>8273371</album_sales_volume> <album name= "Affection" sn= "1st"/> <album name= "grow into one " sn=" 2nd "/> </diva></diva_list>
Above is an example of an XML literal that needs to be imported if the XML text is to be processed.
Import Xml.etree.ElementTree as ET
# because the XML module name is too long, use as to give it an alias, called ET.
Et.parse () reads the XML text directly from the file, parsing the XML text into an XML tree object.
Tree = Et.parse ("Diva.xml")
Gets the root node of the XML tree.
root = Tree.getroot ()
Gets the label (name) of the root node.
Root.tag
#遍历xml文档
For child in Root:
Print (Child.tag, child.attrib)
For I in the child:
Print (I.tag,i.text)
Attention! If you want to take the child node under the XML text, you must go through the root node, and any node is appended with a. Tag can be taken to the tag name in the node, any node plus. Text can be taken to the content contained in each node, attrib can be taken to the attributes that exist in the tag in the node.
# Gets the text content in the Album_sales_volume label for each child node.
For I in Root.iter ("Album_sales_volume"):
Print I.text
# If you want to get the attributes within the tag, just change the text to attrib.
Modify:
For node in Root.iter (' year '):
new_year = Int (node.text) + 1
Node.text = str (new_year) # Modify Content
Node.set ("Flop", "No") # modifies the label properties.
Tree.write ("Xmltest.xml")
Delete:
For country in Root.findall (' Country '):
rank = Int (country.find (' rank '). Text)
If rank > 50:
Root.remove (Country)
Tree.write (' Output.xml ')
Root.findall () is used to find the child node of the specified name, starting from the root node.
Root.remove () is used to delete a node.
generates XML text.
Import Xml.etree.ElementTree as ET
New_xml = ET. Element ("NameList")
Name = ET. Subelement (New_xml, "name", attrib={"enrolled": "Yes"})
Age = ET. subelement (Name, "Age", attrib={"checked": "No"})
Sex = ET. subelement (name, "Sex")
Sex.text = ' 33 '
Name2 = ET. Subelement (New_xml, "name", attrib={"enrolled": "No"})
Age = ET. Subelement (name2, "age")
Age.text = ' 19 '
ET = et. ElementTree (New_xml) #生成文档对象
Et.write ("Test.xml", encoding= "Utf-8", Xml_declaration=true)
Et.dump (New_xml) #打印生成的格式
This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1910450
XML for the 6.python serialization function