1. Basic Concepts
XML is a protocol that implements data exchange between different languages or programs, similar to JSON, but JSON is simpler to use.
However, in ancient times, in the Dark Age when JSON was not yet born, you can only choose to use XML.
So far, many traditional companies such as the financial industry of many systems interface is also mainly XML.
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>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>
XML protocols are supported in each language, and in Python you can manipulate XML with the following modules
2.
遍历xml文档
import 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 Child: print (I.tag,i.text) Span style= "color: #008000;" ># for node in root.iter ( year ' print (Node.tag,node.text)
3. Modify and delete 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')
4. 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 XML module