介紹
由于Python對(duì)XML讀寫(xiě)有多種庫(kù),本文以xml.etree import ElementTree為例。
解析
from xml.etree import ElementTree as ET
############ 解析方式一 ############
# 打開(kāi)文件,讀取XML內(nèi)容
str_xml = open('xo.xml', 'r').read()
# 利用ElementTree.XML將字符串解析成xml對(duì)象,root代指xml文件的根節(jié)點(diǎn)
root = ET.XML(str_xml)
操作XML
XML遍歷
from xml.etree import ElementTree as ET
############ 解析方式二 ############
# 直接解析xml文件
tree = ET.parse("xo.xml")
# 獲取xml文件的根節(jié)點(diǎn)
root = tree.getroot()
### 操作
# 頂層標(biāo)簽
print(root.tag)
# 遍歷XML文檔的第二層
for child in root:
# 第二層節(jié)點(diǎn)的標(biāo)簽名稱和標(biāo)簽屬性
print(child.tag, child.attrib)
# 遍歷XML文檔的第三層
for i in child:
# 第二層節(jié)點(diǎn)的標(biāo)簽名稱和內(nèi)容
print(i.tag,i.text)
# 遍歷XML中所有的year節(jié)點(diǎn)
for node in root.iter('year'):
# 節(jié)點(diǎn)的標(biāo)簽名稱和內(nèi)容
print(node.tag, node.text)
#修改:將year節(jié)點(diǎn)中的內(nèi)容自增一
new_year = int(node.text) + 1
node.text = str(new_year)
# 設(shè)置屬性
node.set('name', 'alex')
node.set('age', '18')
# 刪除屬性
del node.attrib['name']
# 遍歷data下的所有country節(jié)點(diǎn)
for country in root.findall('country'):
# 獲取每一個(gè)country節(jié)點(diǎn)下rank節(jié)點(diǎn)的內(nèi)容
rank = int(country.find('rank').text)
if rank > 50:
# 刪除指定country節(jié)點(diǎn)
root.remove(country)
############ 保存文件 ############
tree = ET.ElementTree(root)
tree.write("new.xml", encoding='utf-8')
## 可能需要的調(diào)整格式
from xml.dom import minidom
def xmlwrite(root,filepath)
rough_string = ET.tostring(root, 'utf-8')
reparsed = minidom.parseString(rough_string)
raw_str = reparsed.toprettyxml(indent='',newl="")
output = open(filepath,'w+',encoding='utf-8')
output.write('<?xml version="1.0" encoding="UTF-8"?> \n <!DOCTYPE topic PUBLIC "-//OASIS//DTD DITA Topic//EN" "topic.dtd">')
output.write(raw_str)
output.close()
http://www.cnblogs.com/lijinrui/p/5619360.html
每個(gè)節(jié)點(diǎn)都具有以上方法,通過(guò)root可以操作整個(gè)xml文件。