Python read-write case sharing for XML files

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.