python解析XML可用的类库或模块有xml、libxml2 、lxml 、xpath等
常用的第三方库对比常用的有三个分别是:xml.etree.ElementTree、xml.dom.*、xml.sax.*
| 第三方库 | 优点 | 缺点 |
|---|---|---|
| xml.etree.ElementTree | 它速度更快,消耗的内存更少 | |
| xml.dom.* | 她文档中所有元素保存在内存中的一个树结构里,利用DOM 提供的不同的函数来读取或修改文档的内容和结构,也可以把修改过的内容写入xml文件 | 消耗内存 |
| xml.sax.* | 一、对大型文件进行处理;二、只需要文件的部分内容,或者只需从文件中得到特定信息;三、想建立自己的对象模型的时候 | ython中使用sax方式处理xml要先引入xml.sax中的parse函数,还有xml.sax.handler中的ContentHandler |
xml.etree.ElementTree在Python标准库中有两种实现:
一种是纯Python实现的,如xml.etree.ElementTree,另一种是速度快一点的xml.etree.cElementTree。从Python 3.3开始ElementTree模块会自动寻找可用的C库来加快速度,所以只需要import xml.etree.ElementTree就可以了
import xml.etree.ElementTree as ET
xml_path = r'DATA_DELETE_SQL.XML'
try:
# 打开xml文档
tree = ET.parse(xml_path)
# 获取root节点
root = tree.getroot()
print(root.tag)
# 通过下标访问
print(root[0][1].tag)
print(root[0][1].text)
except:
print('打不开这个xml')
# 获取根节点下的节点信息
for child in root:
print(child.tag)
print(child.text)
# 获取root节点下的所有 row 节点
for row in root.findall('row'):
print(row.tag)
# 子节点下 TABLE_NAME 节点
table_name = row.find('TABLE_NAME').text
# 子节点下属性的值
table_name_value = row.get('TABLE_NAME')
# 修改xml,移除根节点下所有row节点的 ID节点(注意此移除仅在本次会话中生效,并未修改xml内容)
for row in root.findall('row'):
id = row.find('ID')
row.remove(id)



