xml查询处理
# -*- coding:utf-8 -*-
# Author:chinablue
# tag text attrib
import xml.etree.ElementTree as ET
tree = ET.parse("xmlabc")
root = tree.getroot()
# print root
# print root.tag
#
# # 遍历xml整个文档
# for child in root:
# print child.tag,child.attrib
# for i in child:
# print i.tag,i.text
# 只遍历某个节点
for node in root.iter('age'):
print node.tag,node.text
xml修改处理
# -*- coding:utf-8 -*-
# Author:chinablue
# tag text attrib
import xml.etree.ElementTree as ET
tree = ET.parse("xmlabc")
root = tree.getroot()
# 修改age
for node in root.iter('age'):
new_age = int(node.text) + 1
node.text = str(new_age)
node.set("updated","yes")
tree.write("xmlabc_modify.xml")
xml 删除处理
# -*- coding:utf-8 -*-
# Author:chinablue
# tag text attrib
import xml.etree.ElementTree as ET
tree = ET.parse("xmlabc")
root = tree.getroot()
# 删除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write("output.xml")
xml 创建处理
# -*- coding:utf-8 -*-
# Author:chinablue
# tag text attrib
import xml.etree.ElementTree as ET
new_xml = ET.Element('namelist')
name = ET.SubElement(new_xml,"name",attrib={'enrolled':'yes'})
age = ET.SubElement(name,"age",attrib={'checked':'no'})
sex = ET.SubElement(name,"sex")
age.text = '23'
name2 = ET.SubElement(new_xml,"name",attrib={'enrolled':'yes'})
age = ET.SubElement(name2,"age",attrib={'checked':'no'})
age.text = '33'
# 生成文档对象
et = ET.ElementTree(new_xml)
et.write("create.xml",encoding="utf-8",xml_declaration=True)
ET.dump(new_xml)