XML is a protocol that implements data exchange between different languages or programs, much like JSON, but JSON is simpler to use, but in ancient times, in the Dark Ages when JSON was not yet born, you could only choose to use XML, and so far many traditional companies, such as the financial industry, are mostly XML-like interfaces.
The format of XML is as follows: by the <> node to distinguish the data structure.
<?xml version="1.0"?><data> <country name="Liechtenstein"> <rank updated="Yes">2</rank> <year> -</year> <gdppc>141100</gdppc> <neighbor name="Austria"direction="E"/> <neighbor name="Switzerland"direction="W"/> </country> <country name="Singapore"> <rank updated="Yes">5</rank> <year> .</year> <gdppc>59900</gdppc> <neighbor name="Malaysia"direction="N"/> </country> <country name="Panama"> <rank updated="Yes"> the</rank> <year> .</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica"direction="W"/> <neighbor name="Colombia"direction="E"/> </country></data>
XML protocols are supported in each language, and in Python you can manipulate XML with the following modules
ImportXml.etree.ElementTree as Ettree= Et.parse ("Xmltest.xml") Root=tree.getroot ()Print(Root.tag)#traversing an XML document forChildinchRoot:Print(Child.tag, Child.attrib) forIinchChild :Print(I.tag,i.text)#Traverse only the year node forNodeinchRoot.iter (' Year'): Print(Node.tag,node.text)
modifying and deleting XML document content
ImportXml.etree.ElementTree as Ettree= Et.parse ("Xmltest.xml") Root=tree.getroot ()#Modify forNodeinchRoot.iter (' Year'): New_year= Int (node.text) + 1Node.text=Str (new_year) Node.set ("Updated","Yes") Tree.write ("Xmltest.xml")#Delete Node forCountryinchRoot.findall ('Country'): Rank= Int (Country.find ('Rank'). Text)ifRank > 50: Root.remove (country) tree.write ('Output.xml')
Create your own XML document
ImportXml.etree.ElementTree as Etnew_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=' -'name2= ET. Subelement (New_xml,"name", attrib={"enrolled":"No"}) age= ET. Subelement (Name2," Age") Age.text=' +'et= ET. ElementTree (New_xml)#Generating Document ObjectsEt.write ("Test.xml", encoding="Utf-8", xml_declaration=True) Et.dump (New_xml)#print the generated format
Python Basics-4.10 XML Processing module