This article mainly introduces the details of Python read and write XML file instances of the relevant data, Python generated XML files and Python read XML instance, the need for friends can refer to the following
A detailed example of Python reading and writing XML files
Python generates an XML file
From Xml.dom import minidom# generate XML File Way def generatexml (): impl = Minidom.getdomimplementation () # Create an XML DOM # Three parameters corresponding to: NamespaceURI, QualifiedName, doctype doc = Impl.createdocument (none, none, none) # Create a root element RootElement = doc.createelement (' pythons ') # Add 10 child elements for the root element for Pythonid in range: # Create child elements Childelement = doc.createelement (' python ') # Add id attribute to child element Childelement.setattribute (' id ', str (pythonid)) # Append child elements to the root element Rootelement.appendchild (childelement) print (childElement.firstChild.data) # Append a well-stitched root element to the DOM object doc.appendchild (rootelement) # Open Test.xml file ready to write f = open (' Test.xml ', ' a ') # Write file doc.writexml (F, addindent= ", newl= ' \ n ') # close f.close () # Execute Generate XML Method Generatexml ()
Python read XML file
From xml.dom.minidom import parse# get all ID properties under Python node Def gettagid (): # Get Test.xml Document object doc = Parse ("Test.xml") C2/>for node in doc.getelementsbytagname ("Python"): # Gets the label ID property value_str = Node.getattribute ("id") # printout print (VALUE_STR) # Get Property Idgettagid ()
Run results – Generate XML file as follows
Run Results – Read the XML file as follows