环境
python:3.4.4
准备xml文件
首先新建一个xml文件,countries.xml。内容是在python官网上看到的。
1
2008
141100
4
2011
59900
68
2011
13600
准备python文件
新建一个test_ET.py,用来解析xml文件。
#!/usr/bin/python#-*- coding=utf-8 -*-
importxml.etree.ElementTree as ETfrom xml.etree.ElementTree importElement
tree= ET.parse('countries.xml')
nodes= tree.findall("country")for node innodes:#search node & attribute & text
print ("*****Country*****")if node.attrib["name"]:print ("Name:",node.attrib["name"])
rank=node.find("rank")print ("Rank:",rank.text)
year=node.find("year")print ("Year:",year.text)
gdppc=node.find("gdppc")print ("Gdppc:",gdppc.text)
neighbors=node.findall("neighbor")for neighbor inneighbors:print ("Neighbor:",neighbor.attrib["name"])#add node
rank=node.find("rank")
element=Element("rank_next", {"name":"Rank","create":"20151231"})
element.text="5"rank.append(element)#delete node
year=node.find("year")
node.remove(year)#add node attribute
node.set("force","NewForce")#update node attribute
node.set("name","NewNode")#delete node attribute
neighbors=node.findall("neighbor")for neighbor inneighbors:del neighbor.attrib["direction"]#add node text
neighbors=node.findall("neighbor")for neighbor inneighbors:
neighbor.text= "Hello,Neighbor"
#update node text
gdppc=node.find("gdppc")
gdppc.text= "11111"
#delete node text
rank=node.find("rank")
rank.text= ""tree.write("./out.xml", encoding="utf-8",xml_declaration=True)
执行结果
控制台:
>python test_ET.py*****Country*****Name: Liechtenstein
Rank:1Year:2008Gdppc:141100Neighbor: Austria
Neighbor: Switzerland*****Country*****Name: Singapore
Rank:4Year:2011Gdppc:59900Neighbor: Malaysia*****Country*****Name: Panama
Rank:68Year:2011Gdppc:13600Neighbor: Costa Rica
Neighbor: Colombia
out.xml文件:
5
11111
Hello,Neighbor
Hello,Neighbor
5
11111
Hello,Neighbor
5
11111
Hello,Neighbor
Hello,Neighbor
备注
具有方便友好的API。代码可用性好,速度快,消耗内存少。
最适合用来处理XML文档。
tree = ET.parse('countries.xml')
解析countries.xml并返回一个树。
tree.write("./out2.xml", encoding="utf-8",xml_declaration=True)
将元素树写入到文档,采用 “utf-8”编码,具有xml声明。
write(file, encoding="us-ascii", xml_declaration=None, default_namespace=None, method="xml")
Writes the element tree to a file, as XML. file is a file name, or a file object opened for writing. encoding [1] is the output encoding (default is US-ASCII). xml_declaration controls if an XML declaration should be added to the file. Use False for never, True for always, None for only if not US-ASCII or UTF-8 (default is None). default_namespace sets the default XML namespace (for “xmlns”). method is either "xml", "html" or "text" (default is "xml"). Returns an encoded string.