Create an XML document using PYTHON

Source: Internet
Author: User

When GOOGLE is used for query, the content is almost the same. But none of the things you want. For example, I cannot find how to use PYTHON to create an XML file written by the Chinese. Of course, direct file writing can achieve the same effect, but after all, it is prone to errors and looks not elegant. Finally, I read a lot of documents and finally learned how to use PYTHON to write an XML file. The following is a simple example. This example has been debugged and can be used with ease. Copy codeThe Code is 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, I want to create an xml file using python. I found not many documents, and basically used python to parse xml files.
For exampleCopy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Root>
<Book isbn = "34909023">
<Author>
Dikatour
</Author>
</Book>
</Root>

Write to the xmlstuff. xml file.
The basic principle is as follows:
Using the xml DOM method, I first create an empty DOM tree in the memory, then add the nodes I want, and finally form the DOM that I want, output to the file.
1. I use the module xml. dom. minidom to create an xml file.
From xml. dom import minidom
2. Each xml file is a Document object, representing the DOM tree in the memory.
Doc = minidom. Document ()
3. After an empty DOM tree is available, we can add the root node to it.
RootNode = doc. createElement ("root ")
Doc. appendChild (rootNode) # note that the Node object is not added to the DOM tree after createElement in python library reference. You must manually add
4. create other nodes
5. output to the xml file
Doc. writexml (f, "/t", "/t", "/n", "UTF-8") # The first parameter f is your target file object, the second parameter seems to be <? Xml> and the indent arrangement format of the following root node,
The third parameter seems to be the indent arrangement format of other nodes and subnodes, and the fourth parameter defines the line feed format (if you fill in "", it will not wrap, all xml files are saved on one line)
The fifth parameter specifies the encoding of the xml content. Except that the first parameter is required, other parameters are optional.
The final code is as follows (this program has no value but is used to test and verify your own ideas. You are more likely to define a simple class or function to serialize your data structure to an xml file ):Copy codeThe Code is 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 t:
Trackback. print_exc ()
Finally:
F. close ()
Except t IOException:
Print "open file failed"

Summary:
1. Target (write a string of xml strings to a file) => get a string of xml strings => dom tree (the toxml method in the mini DOM outputs xml Information of the dom tree as a string)
2. use Chapter 2.5 (structrued Markup Processing Tools) in the library reference in python 8th documentation (that is, the python manual installed together when python is installed). It is important to check the manual, read some concise python books
3. The logic is clear and I have no idea about how to use python to manipulate xml, just look at the information to complete the function.
4. It Exactly proves the powerful functionality of the python language 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.