<?xml version="1.0"?>
<yaobin>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2012</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</yaobin>
#!/usr/bin/env python
#coding=utf-8
import xml.etree.cElementTree as ET
tree=ET.parse("test.xml")
root=tree.getroot()
print(root.tag)
for child in root:
print(child.tag,child.attrib)
for i in child:
print("---->",i.tag,i.text)
for node in root.iter(‘year‘):
print(node.tag,node.text)
#!/usr/bin/env python
#coding=utf-8
import xml.etree.cElementTree as ET
tree=ET.parse("test.xml")
root=tree.getroot()
print(root.tag)
for node in root.iter(‘year‘):
new_year=int(node.text) +100
node.text=str(new_year)
node.set("new_attrib","attrib_value")
tree.write("new_test.xml")
for country in root.findall(‘country‘):
rank=int(country.find(‘rank‘).text)
if rank >50:
root.remove(country)
tree.write("new_test2.xml")
#!/usr/bin/env python
#coding=utf-8
import xml.etree.ElementTree as ET
new_xml = ET.Element("namelist") #root
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
age.text = ‘33‘
sex.text="boy"
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
sex = ET.SubElement(name2,"sex")
age.text = ‘19‘
sex.text=‘girl‘
et = ET.ElementTree(new_xml) #生成文档对象
et.write("my_test.xml", encoding="utf-8",xml_declaration=True)
ET.dump(new_xml) #打印生成的格式
原文:http://www.cnblogs.com/binhy0428/p/5221244.html