SoFunction
Updated on 2024-11-16

Examples of python operations to write xml files

This article example describes the method of python write xml file operation, shared for your reference. Specific methods are as follows:

The format of the xml file to be generated is as follows:

<?xml version="1.0" ?> 
<!--Simple xml document__chapter 8--> 
<book> 
  <title> 
    sample xml thing 
  </title> 
  <author> 
    <name> 
      <first> 
        ma 
      </first> 
      <last> 
        xiaoju 
      </last> 
    </name> 
    <affiliation> 
      Springs Widgets, Inc. 
    </affiliation> 
  </author> 
  <chapter number="1"> 
    <title> 
      First 
    </title> 
    <para> 
      I think widgets are  should buy lots of them forom 
      <company> 
        Spirngy Widgts, Inc 
      </company> 
    </para> 
  </chapter> 
</book> 

The Python implementation code is as follows:

from  import minidom, Node 
 
doc = () 
 
(("Simple xml document__chapter 8")) 
 
#generate the book 
book = ('book') 
(book) 
 
#the title 
title = ('title') 
(("sample xml thing")) 
(title) 
 
#the author section 
author = ("author") 
(author) 
name = ('name') 
(name) 
firstname = ('first') 
(("ma")) 
(firstname) 
lastname = ('last') 
(lastname) 
(("xiaoju")) 
 
affiliation = ("affiliation") 
(("Springs Widgets, Inc.")) 
(affiliation) 
 
#The chapter 
chapter = ('chapter') 
('number', '1') 
title = ('title') 
(("First")) 
(title) 
(chapter) 
 
para = ('para') 
(("I think widgets are greate.\ 
You should buy lots of them forom")) 
company = ('company') 
(("Spirngy Widgts, Inc")) 
(company) 
(para) 
 
print () 

I hope that what I have described in this article will help you in your Python programming.