This article describes the Python writing XML file operation method, share for everyone for reference. The specific methods are as follows:
The XML file format 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>
</title>
<para>
I widgets are greate. Should buy lots of them forom
<company>
spirngy widgts, Inc
</company>
</para >
</chapter>
</book>
The Python implementation code is as follows:
From xml.dom import Minidom, Node doc = Minidom. Document () Doc.appendchild (Doc.createcomment ("Simple XML Document__chapter 8") #generate the book book = Doc.creat Eelement ("book") Doc.appendchild (book) #the title title = doc.createelement (' title ') Title.appendchild (Doc.createtex Tnode ("Sample XML Thing")) Book.appendchild (title) #the Author Section author = doc.createelement ("author") Book.app Endchild (author) name = doc.createelement (' name ') author.appendchild (name) FirstName = doc.createelement (' i ') firs
Tname.appendchild (Doc.createtextnode ("Ma")) Name.appendchild (firstname) LastName = Doc.createelement (' last ') Name.appendchild (LastName) Lastname.appendchild (Doc.createtextnode ("Xiaoju")) affiliation = Doc.createelement ("
Affiliation ") Affiliation.appendchild (Doc.createtextnode (" Springs Widgets, Inc. ") Author.appendchild (Affiliation) #The Chapter Chapter = doc.createelement (' chapter ') Chapter.setattribute (' Number ', ' 1 ') title = Doc.createelemENT (' title ') Title.appendchild (Doc.createtextnode ("the") Chapter.appendchild (title) Book.appendchild (chapter) Para = doc.createelement (' para ') para.appendchild (Doc.createtextnode ("I I-I-I-am widgets are greate.\ you should buy lots o F them Forom ")" Company = Doc.createelement (' company ') Company.appendchild (Doc.createtextnode ("Spirngy Widgts, Inc")) p
Ara.appendchild (company) Chapter.appendchild (para) print doc.toprettyxml ()
I hope this article will help you with your Python programming.