Write XML files in Python
May 29, 13:54:38
Add to favorites I want to contribute
The format of the XML file to be generated is as follows:
[Python]
<? 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 greate. You shoshould buy lots of them forom
<Company>
Spirngy widgts, Inc
</Company>
</Para>
</Chapter>
</Book>
Code:
[Python]
From XML. Dom import minidom, node
Doc = minidom. Document ()
Doc. appendchild (Doc. createcomment ("simple XML document _ Chapter 8 "))
# Generate the book
Book = Doc. createelement ('book ')
Doc. appendchild (book)
# The title
Title = Doc. createelement ('title ')
Title. appendchild (Doc. createtextnode ("sample XML thing "))
Book. appendchild (title)
# The author Section
Author = Doc. createelement ("author ")
Book. appendchild (author)
Name = Doc. createelement ('name ')
Author. appendchild (name)
Firstname = Doc. createelement ('first ')
Firstname. 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 ("first "))
Chapter. appendchild (title)
Book. appendchild (chapter)
Para = Doc. createelement ('para ')
Para. appendchild (Doc. createtextnode ("I think widgets are greate .\
You shoshould buy lots of them forom "))
Company = Doc. createelement ('company ')
Company. appendchild (Doc. createtextnode ("spirngy widgts, Inc "))
Para. appendchild (company)
Chapter. appendchild (para)
Print Doc. toprettyxml ()