Python 常用函数 xml模块

时间:2022-12-29 22:40:26

XML 指可扩展标记语言(eXtensible Markup Language)。

XML 被设计用来传输和存储数据。

XML是一套定义语义标记的规则,这些标记将文档分成许多部件并对这些部件加以标识。

它也是元标记语言,即定义了用于定义其他与特定领域有关的、语义的、结构化的标记语言的句法语言。

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>

 

常用操作:

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml') #打开想xml文档
root = tree.getroot() #获得根节点
#遍历xml文档
for child in root:
print('========>', child.tag, child.attrib, child.attrib['name'])
for i in child:
print(i.tag, i.attrib, i.text)

#查找element元素的三种方式之iter
years = root.iter('year') #从根节点下开始扫描所有树形结构
for i in years:
print(i)
print(i.text)
#查找element元素的三种方式之find
res = root.find('country') #从根下一层开始查找,返回一个与之匹配的元素
print(res)

#查找element元素的三种方式之findall
res = root.findall('country') #从根下一层开始查找,返回所有与之匹配的元素
print(res)

#修改节点
for node in root.iter('year'):
new_year = int(node.text)+1 #拿出year里面的内容,转成整型再进行加1操作
node.text = str(new_year) #转成字符串类型,才能写入文件
node.set('updated','yes') #添加属性
node.set('version','1.0') #添加属性
tree.write('test.xml')

#删除节点
for country in root.findall('country'):
rank = country.find('rank')
if int(rank.text) > 50:
country.remove(rank)
tree.write('test.xml')

#增加节点
for country in root.findall('country'):
y = ET.Element('Yim')
y.attrib = {'age':'25'}
y.text = 'hello'
country.append(y)
tree.write('test.xml')

创建xml文档:

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")
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)
ET.dump(new_xml) # 打印生成的格式