XML Module Introduction
As with JSON, protocols for data exchange in different languages and programs. But JSON is easier to use and has a tendency to replace XML. Now most financial data providers (e.g. Bloombegy) are still using XML.
In Python, generate and parse XML files with the import Xml.etree.ElementTree module
Format of the XML file
The format of XML is as follows: by the <> node to distinguish the data structure.
Format common operations for XML
Read XML
ImportXml.etree.ElementTree as Ettree= Et.parse ("Xmltest.xml") Root=tree.getroot ()Print(Root.tag)#Back to Data#Calendar XML Documents forChildinchRoot:Print(Child.tag, Child.attrib)#return to country layer forIinchChild :Print(I.tag, I.text)#only calendar year node, select data Calendar forNodeinchRoot.iter (" Year"): Print(Node.tag,node.text)
Read XML
Modify the contents of the delete XML file
ImportXml.etree.ElementTree as Ettree= Et.parse ("Xmltest.xml") Root=tree.getroot ()#Modifying Data forNodeinchRoot.iter (" Year"): New_year= Int (node.text) + 1#1 increase every yearNode.text = str (new_year)#Assign ValueNode.set ("Updated","Yes")#Also, modify the Attribution propertyTree.write ("Xmltest.xml")#Delete a node forCountryinchRoot.findall ("Country"): Rank= Int (Country.find ('Rank'). Text)ifRank > 50: Root.remove (country) tree.write ("Output.xml")
Modify and delete
Create a new XML file
ImportXml.etree.ElementTree as Etnew_xml= ET. Element ("NameList")#Creating the root nodePersoninfo = ET. Subelement (New_xml,"Personinfo", attrib={"enrolled":"yea"}) name= ET. Subelement (Personinfo,"name") Name.text="Alex Li" Age= ET. Subelement (Personinfo," Age", attrib={"checked":"No"}) Age.text=" About"Sex= ET. Subelement (Personinfo,"Sex") Sex.text="F"Personinfo2= ET. Subelement (New_xml,"Personinfo", attrib={"enrolled":"Yes"}) name= ET. Subelement (Personinfo2,"name") Name.text="Oldboy ran" Age= ET. Subelement (Personinfo2," Age") Age.text=" A"et= ET. ElementTree (New_xml)#Generating Document ObjectsEt.write ("New_xml_test.xml", encoding="Utf-8", xml_declaration=True) Et.dump (New_xml)#print the generated format
Create
Python Basics-Day 5 learning note-Standard library of modules: XML (9)