使用Python讀寫XML檔案

2021-05-28 11:29:49 字數 2296 閱讀 5575

from xml.etree.elementtree import elementtree

from 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", )

print item.items() # [('sku', '33-993933'), ('qty', '4')]

print item.attrib #

print item.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

print purchaseorder.find('account')

print purchaseorder.find('account').get('refnum')

print purchaseorder.findall('account')[0].get('refnum')

print purchaseorder.find('item/name')

print purchaseorder.find('item/name').text

## how to use elementtree([element,] [file])

## 1. from standard xml element, it becomes root element

print elementtree(item).getroot().find('name').text

## 2. from xml file

print elementtree(file='book.xml').getroot().find('item/description').text

## create an iterator

for element in purchaseorder.getiterator():

print element.tag

## get pretty look

def indent(elem, level=0):

i = "\n" + level*" "

if len(elem):

if not elem.text or not elem.text.strip():

elem.text = i + " "

for e in elem:

indent(e, level+1)

if not e.tail or not e.tail.strip():

e.tail = i

if level and (not elem.tail or not elem.tail.strip()):

elem.tail = i

return elem

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...

使用TinyXML讀 寫XML檔案

1 tinyxml 引用網上的原話 tinyxml是目前非常流行的一款基於dom模型的xml解析器,簡單易用且小巧 玲瓏,非常適合儲存簡單資料,配置檔案,物件序列化等資料量不是很大的操作。支援對xml的讀取和修改,不直接支援xpath,需要借助另乙個相關的類庫tinyxpath才可以支援xpath ...

讀寫XML檔案

1.將xml資料寫入檔案 寫入xml 傳入obj得型別 儲存得檔案路徑 要儲存得資料 public void writeobjecttofile string filename,t obj 2.從檔案中讀取xml資料,並序列化為物件 從檔案中讀取資料到xml檔案 返回型別 讀取的檔案路徑 publi...