python寫xml文件的操作實(shí)例
本文實(shí)例講述了python寫xml文件的操作的方法,分享給大家供大家參考。具體方法如下:
要生成的xml文件格式如下:
<?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 should buy lots of them forom
<company>
Spirngy Widgts, Inc
</company>
</para>
</chapter>
</book>
Python實(shí)現(xiàn)代碼如下:
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 should 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()
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
如何實(shí)現(xiàn)一個(gè)python函數(shù)裝飾器(Decorator)
這篇文章主要介紹了如何實(shí)現(xiàn)一個(gè)python函數(shù)裝飾器(Decorator),幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-10-10
pyinstaller打包單個(gè)exe后無法執(zhí)行錯(cuò)誤的解決方法
今天小編就為大家分享一篇pyinstaller打包單個(gè)exe后無法執(zhí)行錯(cuò)誤的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python requests模塊基礎(chǔ)使用方法實(shí)例及高級(jí)應(yīng)用(自動(dòng)登陸,抓取網(wǎng)頁源碼)實(shí)例詳解
這篇文章主要介紹了Python requests模塊基礎(chǔ)使用方法實(shí)例及高級(jí)應(yīng)用(自動(dòng)登陸,抓取網(wǎng)頁源碼,Cookies)實(shí)例詳解,需要的朋友可以參考下2020-02-02
Python for Informatics 第11章之正則表達(dá)式(四)
這篇文章主要介紹了Python for Informatics 第11章之正則表達(dá)式(四) 的相關(guān)資料,需要的朋友可以參考下2016-04-04
Django中QuerySet查詢優(yōu)化之prefetch_related詳解
prefetch_related()和select_related()的設(shè)計(jì)目的很相似,都是為了減少SQL查詢的數(shù)量,但是實(shí)現(xiàn)的方式不一樣,下面這篇文章主要給大家介紹了關(guān)于Django中QuerySet查詢優(yōu)化之prefetch_related的相關(guān)資料,需要的朋友可以參考下2022-11-11
python讀取浮點(diǎn)數(shù)和讀取文本文件示例
這篇文章主要介紹了python讀取浮點(diǎn)數(shù)和讀取文本文件示例,需要的朋友可以參考下2014-05-05

