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.
1, the format of the XML is as follows, is through the <> node to distinguish the data structure:
<?xml version= "1.0"?><data><countryName="Liechtenstein"><rankUpdated="Yes">2</rank><year>2008</year><gdppc>141100</gdppc><neighborName="Austria"Direction="E"/><neighborName="Switzerland"Direction="W"/></country><countryName="Singapore"><rankUpdated="Yes">5</rank><year>2011</year><gdppc>59900</gdppc><neighborName="Malaysia"Direction="N"/></country><countryName="Panama"><rankUpdated="Yes">69</rank><year>2011</year><gdppc>13600</gdppc><neighborName="Costa Rica"Direction="W "/> <neighbor name< Span class= "token punctuation" >= "Colombia" direction=" E "/> </country></data< Span class= "token punctuation" >>
2, the XML protocol in each language is supported, in Python can use the following modules to manipulate XML
Import XML. etree. ElementTreeAs Ettree= ET. Parse("Xmltest.xml") root= Tree. getroot()Print(Root. Tag)#遍历xml文档For childIn Root:Print(Child. Tag, child. attrib)for I in the child: print(i. Tag, I. Text) #只遍历year nodes for node in root. ITER(' year '): Print(node. Tag, node. Text)
modifying and deleting XML document content
Import XML. etree. ElementTreeAs Ettree= ET. Parse("Xmltest.xml") root= Tree. getroot()#修改For nodeIn Root. iter(' Year '): New_year= int(node. text)+1 node. text= str(New_year) node. Set("Updated","Yes") tree. Write("Xmltest.xml")#删除nodeFor countryIn Root. findall ( ' country ' : Rank = int.find ( ' rank ' ) .text) if rank > 50: Root.remove.write ( ' output.xml ' )
3. Create your own XML document
Import XML. etree. ElementTreeAs 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".text = "et = et #生成文档对象et .write "Test.xml" = "Utf-8" ,xml_declaration=true) Et.dump (New_xml
Python base-xml module