XML处理

xmltest.xml内容如下:

<?xml version="1.0"?>
<data>
<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>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>

-------------------------------------------------------------
查找xml信息:

import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root)
print(root.tag) #最外面的标签名

# 遍历xml文档
for child in root:
print(child.tag, child.attrib)#child.tag标签名,child.attrib 属性信息
for i in child:
print(i.tag, i.text) #i.text,string对象,表示element的内容。
# 只遍历year 节点
for node in root.iter('year'):
print(node.tag, node.text)

ElementTree提供的方法:
find(match)                                                    # 查找第一个匹配的子元素, match可以时tag或是xpaht路径
findall(match) # 返回所有匹配的子元素列表
findtext(match, default=None) #查找匹配匹配的第一个子元素的文本
iter(tag=None) # 以当前元素为根节点 创建树迭代器,如果tag不为None,则以tag进行过滤
iterfind(match) #按标签名称或路径查找所有匹配的子元素。 返回一个迭代,以文档顺序生成所有匹配的元素.

-------------------------------------------------------------
修改xml

import xml.etree.ElementTree as ET

tree = ET.parse("xmltest.xml")
root = tree.getroot() #返回此xml的根元素

# 修改
for node in root.iter('year'):
new_year = int(node.text) + 1
node.text = str(new_year) #转换为str,因为int不是可迭代的
node.set("updated", "yes")
print(node.text)

tree.write("xmltest.xml")

# 删除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
print (rank)
if rank > 50:
root.remove(country)

tree.write('xmltest.xml')

-------------------------------------------------------------
创建xml:

import xml.etree.ElementTree as ET
new_xml = ET.Element("namelist") #最外面的标签名
name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})#二级标签名name,属性enrolled="yes";new_xml是父元素,name是子元素, attrib是一个可选字典,包含元素属性
age = ET.SubElement(name, "age", attrib={"checked": "no"})
sex = ET.SubElement(name, "sex")
sex.text = '33'
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '19'

et = ET.ElementTree(new_xml) # 生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True)#encoding是输出编码,xml_declaration控制是否应将XML声明添加到文件中,使用为True,不使用为False

ET.dump(new_xml) # 打印生成的格式

参考:
https://www.cnblogs.com/alex3714/articles/5161349.html
https://docs.python.org/3/library/xml.etree.elementtree.html?highlight=findtext#xml.etree.ElementTree.Element.findtext



posted @ 2018-09-04 14:01  只记今朝笑  阅读(220)  评论(0编辑  收藏  举报