Creating XML documents using Python _python

Source: Internet
Author: User
When Google is used, the content is almost always the same. But none of the things you want. For example, I couldn't find the Chinese writing how to use Python to create an XML file. Of course, writing directly to the file can achieve the same effect, but it is easy to make mistakes, and looks not elegant. Finally, I read a lot of information and finally figured out how to write an XML file using Python. The following is a simple example, this example is already debugging passed, we can rest assured that the use.
Copy Code code as follows:

Import Xml.dom.minidom
From xml.dom.DOMImplementation Import implementation
Import Xml.sax.writer
Import Xml.utils

# Create a new document with no namespace URI, qualified name,
# or Document Type
Document = Implementation.createdocument (None,none,none)
Personnel = Document.createelement ("Personnel")
Personnel.setattribute (' Number ', ' 5 ')
Document.appendchild (Personnel)
Sexnode = document.createelement ("Sex")
Sexnode.appendchild (document.createTextNode ("male"))

Namenode = document.createelement ("name")
Namenode.appendchild (document.createTextNode ("Tianbin"))

Personnel.appendchild (Sexnode)
Personnel.appendchild (Namenode)

out = open ("Tianbin.xml", "W")
Xml.dom.ext.PrettyPrint (Document,out)


Today you want to use Python to create an XML file. Looked for the data, found that the data is not many, basically using Python to parse the XML file.
For example, I would like to include content
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<root>
<book isbn= "34909023" >
<author>
Dikatour
</author>
</book>
</root>

Write to the Xmlstuff.xml file.
In fact, it is very simple, the basic principle is as follows:
I use the DOM method of XML to create an empty DOM tree in memory first, then add the node I want, and finally I want the DOM and finally output it to the file.
1. I use the Xml.dom.minidom module to create an XML file
From Xml.dom import Minidom
2. Each XML file is a Document object that represents the DOM tree in memory
Doc = Minidom. Document ()
3. With the empty DOM tree, we add the root node above
RootNode = doc.createelement ("root")
Doc.appendchild (RootNode) #注意python的library reference said that after createelement did not add the node object to the DOM tree, you need to manually add
4. Create additional nodes
5. Output to XML file
Doc.writexml (F, "/t", "/t", "N", "Utf-8") #第一个参数f就是你的目标文件对象, the second parameter seems to be the indented arrangement of <?xml> and one of the following root nodes.
The third parameter seems to be the indented arrangement of other nodes and child nodes, and the fourth parameter has a format for wrapping (if you fill in "", it's not a newline, all the XML is indented on one line:))
, the fifth parameter encodes the XML content. Other parameters are optional except that the first argument is required.
The final code is as follows (this program is worthless, just testing your own ideas, you're more likely to define a simple class or function that serializes your data structure into an XML file):
Copy Code code as follows:

From Xml.dom import Minidom
Import Traceback
Try
f = open ("Xmlstuff.xml", "W")
Try
Doc = Minidom. Document ()
RootNode = doc.createelement ("root")
Doc.appendchild (RootNode)
Booknode = Doc.createelement ("book")
Booknode.setattribute ("ISBN", "34909023")
Rootnode.appendchild (Booknode)
Authornode = Doc.createelement ("author")
Booknode.appendchild (Authornode)
Authortextnode = Doc.createtextnode ("Dikatour")
Authornode.appendchild (Authortextnode)
Doc.writexml (F, "/t", "/t", "/n", "Utf-8")
Except
Trackback.print_exc ()
Finally
F.close ()
Except IOException:
Print "Open file failed"

Summarize:
1. Goal (writes a string of XML strings to a file) => gets a string of XML strings =>dom tree (Minidom has ToXml method to output the DOM tree's XML information as a string)
2. Chapter 8th (structrued Markup processing Tools) in the library reference in the Python 2.5 documentation (the Python manual installed with Python) It's important to consult a handbook, and check out some concise Python books.
3. Think more, logic clear, instant as I do not know how to manipulate XML using Python, a little bit of information can be completed function
4. The powerful functionality of the Python language is proving to be:) gets job done.

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.