要生成的xml檔案格式如下:
[python]
<?xml version="1.0" ?>
sample xml thing
ma xiaoju
springs widgets, inc.
first
i think widgets are greate.you should buy lots of them forom
spirngy widgts, inc
以前用python中的minidom寫過生成xml檔案的程式,現在需要讀取xml檔案中的內容了,首先想到的還是minidom模組.一番編寫測試後,如願掌握了其函式的使用方式,和ajax中的dom操作沒什麼區別.
以前就知道elementtree在處理xml檔案時廣受python程式設計師的歡迎,也安裝過elementtree的安裝包,現在使用的python2.5中已將其收錄了.既然我要處理xml檔案,當然也要學著使用更高效和易用的模組了.自己摸索了半天,除了有關名字空間的函式沒有試用外,其它函式都試用過了.以後處理xml檔案可以得心應手了。
下面是乙個簡單的例子,通過它可以知道各個函式的使用方法:
from xml.etree.elementtree import elementtreefrom xml.etree.elementtree import element
from xml.etree.elementtree import subelement
from xml.etree.elementtree import dump
from xml.etree.elementtree import comment
from xml.etree.elementtree import tostring
'''<?xml version="1.0"?>
potato smasher
smash potatoes like never before.
'''## writing the content to xml document
book = elementtree()
purchaseorder = element('purchaseorder')
book._setroot(purchaseorder)
subelement(purchaseorder, 'account', )
item = element("item", )
printitem.items() # [('sku', '33-993933'), ('qty', '4')]
printitem.attrib #
printitem.get('sku') # 33-993933
subelement(item, 'name').text = "potato smasher"
subelement(item, 'description').text = "smash potatoes like never before."
#book.write('book.xml',"utf-8")
#print tostring(purchaseorder)
#import sys
#book.write(sys.stdout)
#dump(book)
## displaying the content of the xml document
printpurchaseorder.find('account')
printpurchaseorder.find('account').get('refnum')
printpurchaseorder.findall('account')[0].get('refnum')
printpurchaseorder.find('item/name')
printpurchaseorder.find('item/name').text
## how to use elementtree([element,] [file])
## 1. from standard xml element, it becomes root element
printelementtree(item).getroot().find('name').text
## 2. from xml file
printelementtree(file='book.xml').getroot().find('item/description').text
## create an iterator
forelementinpurchaseorder.getiterator():
printelement.tag
## get pretty look
defindent(elem, level=0):
i = "\n" + level*""
iflen(elem):
ifnotelem.textornotelem.text.strip():
elem.text = i + ""
foreinelem:
indent(e, level+1)
ifnote.tailornote.tail.strip():
e.tail = i
ifleveland(notelem.tailornotelem.tail.strip()):
elem.tail = i
returnelem
if__name__=="__main__":
dump(indent(purchaseorder))
book.write('book.xml',"utf-8")
python讀寫xml檔案
xml檔案是具有樹狀結構的,如果想要訪問某個葉子結點,必須逐層獲取其父結點,要讀取某個葉子結點內容用text成員 使用前先載入xml工具包 try import xml.etree.celementtree as et except importerror import xml.etree.elem...
使用Python讀寫XML檔案
from xml.etree.elementtree import elementtree from xml.etree.elementtree import element from xml.etree.elementtree import subelement from xml.etree.el...
讀寫XML檔案
1.將xml資料寫入檔案 寫入xml 傳入obj得型別 儲存得檔案路徑 要儲存得資料 public void writeobjecttofile string filename,t obj 2.從檔案中讀取xml資料,並序列化為物件 從檔案中讀取資料到xml檔案 返回型別 讀取的檔案路徑 publi...