XML processing: XML is the implementation of different languages or programs to exchange data between the protocol, like JSON, but JSON is more simple to use, in the dark era of JSON has not been born, we can only choose to use XML Ah, so far many traditional companies such as the financial industry, many systems interface is mainly XML. Document Format: He uses the <> node to differentiate the data structure:
Document Format
<?xml version= "1.0"? ><data> <country name= "Liechtenstein" > <rank updated= "yes" >2</rank><year>2008</year> <gdppc>141100</gdppc> <neighbor name= " Austria "direction=" E "/> <neighbor name=" Switzerland "direction=" W "/> </country> <country name= "Singapore" > <rank updated= "yes" >5</rank> <year>2011</year > <gdppc>59900</gdppc> <neighbor name= "Malaysia" direction= "N"/> </ Country> <country name= "Panama" > <rank updated= "yes" >69</rank><year>2011 </year> <gdppc>13600</gdppc> <neighbor name= "Costa Rica" direction= "W"/> <neighbor name= "Colombia" direction= "E"/> </country></data>
#python操作xml协议: Import Xml.etree.ElementTree as Etimport xml.etree.ElementTree as Ettree = Et.parse ("xmltest.xml") root = Tree.getroot () print (Root.tag) # Traverse XML document for child in Root:print (Child.tag, Child.attrib) for I in Child:print (I.tag, I.text) # Traverse only the year node for node in Root.iter (' year '): Print (Node.tag, node.text) #修改和删除xml文档内容import Xml.etree.Eleme Nttree as Ettree = Et.parse ("xmltest.xml") root = Tree.getroot () # Modify for node in Root.iter (' year '): new_year = Int (node.t EXT) + 1 node.text = str (new_year) Node.set ("Updated", "yes") tree.write ("Xmltest.xml") # Delete Nodefor country in root.fi Ndall (' country '): rank = Int (country.find (' rank '). Text) if rank > 50:root.remove (Country) tree.write (' OUTP Ut.xml ') # Create an XML document yourself import Xml.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) # Generate Document Object Et.write ("Test.xml", encoding= "Utf-8", Xml_declaration=true) Et.dump (new_xml) # Print generated format
Python XML module