Python 标准库

ElementTree

2022-05-26

import:: import xml.etree.ElementTree as ET

doc:: xml.etree.ElementTree


解析

1
import xml.etree.ElementTree as ET
2
3
# 解析 xml 文件
4
tree = ET.parse('country_data.xml')
5
# 解析字符串
6
str= '<?xml version="1.0" encoding="UTF-8"?><PTZData><pan>0</pan><tilt>0</tilt></PTZData>'
7
tree = ET.fromstring(str)

version: “1.0” 会报错 xml.etree.ElementTree.ParseError: XML declaration not well-formed,此时改为 ==version=“1.0”== 即可。

ET.dump(<xml) : 输出 XML

获取

1
# 获取标签
2
tree.tag
3
4
# 获取文本
5
tree.text

构造

1
import xml.etree.ElementTree as ET
2
3
zero = ET.Element('root') # 标签名
4
one = ET.SubElement(zero, 'num') # 节点名
5
one.text = '42' # 为节点赋值
6
7
head = '<?xml version="1.0" encoding="UTF-8"?>'
8
head += ET.tostring(zero, encoding='UTF-8').decode('utf-8')
9
# 返回 <?xml version="1.0" encoding="UTF-8"?><root><num>42</num></root>