本文介绍了Python中处理XML的三种方式:DOM、SAX和ElementTree。ElementTree模块提供了轻量级的API,既兼顾速度又易于使用。示例展示了如何解析XML文件、获取根节点、读取节点内容、查找和修改节点,以及删除和构建XML文件。
解析xml文件并获取根节点:
from xml.etree import ElementTree as ET
# 1、打开xml文件
tree =ET.parse(r"E:\Acctrue2.0Test\testData\N0530YPYM001.xml")
# 获xml文件的内容取根标签
root = tree.getroot()
print(root)
注意xml格式的内容应该没有xml格式声明的内容“<?xml version="1.0" encoding="UTF-8"?>”,
如果有则会解析错误:
content = """
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="关联关系XML Schema-3.0.xsd" License="">
<Events version="3.0">
<Event name="RelationCreate">
<Relation productCode="06970593810109" subTypeNo="06970593810109" cascade="1" packageSpec="50人份/盒" comment="" linkProductCode="" assCorpCode="">
<Batch batchNo="N0530001" madeDate="2022-05-30" validateDate="2023-05-29" workshop="无" lineName="无" lineManager="无">
<Code curCode="010697059381010910N053000117230527" packLayer="1" parentCode="" flag="0" />
</Batch>
</Relation>
</Event>
</Events>
</Document>
"""
root2= ET.XML(content)
print(root2)
获取标签名,获取标签属性及获取标签文本:
# 1、打开xml文件
tree =ET.parse(r"E:\Acctrue2.0Test\testData\N0530YPYM001.xml")
# 获xml文件的内容取根标签
root = tree.getroot()
# 2、读取节点内容
# 2.1 获取根标签下的子标签
for child in root: 获取根节点下的子标签
print(child.tag) # *.tag 是获取标签名字(字符串类型)
print( child.attrib) # *.attrib是获取标签属性(字典类型)
for node in child: 获取跟标签下子标签的子标签
print(node.tag)
print(node.attrib)
print(node.text) # *.text 获取标签文本
find() # 此种写法只能获取根标签下的一级子标签,即只能查询下一级标签,不能查询到下一级的下一级标签,且找到的是第一个相应的标签
findall()此种写法只能获取根标签下的一级子标签,即只能查询下一级标签,不能查询到下一级的下一级标签 ,但是找到下一级的所有符合名称的标签
# 1、打开xml文件
from xml.etree import ElementTree as ET
# 1、打开xml文件
from xml.etree import ElementTree as ET
tree =ET.parse(r"E:\Acctrue2.0Test\testData\N0530YPYM001.xml")
# 获xml文件的内容取根标签
root = tree.getroot()
print(root)
# 2.2 通过标签名称获取标签 find()
events_object = root.find("Events") # 此种写法只能获取根标签下的一级子标签,即只能查询下一级标签,不能查询到下一级的下一级标签,**且找到的是第一个响应的标签**
print(events_object.tag, events_object.attrib)
event_object = events_object.find("Event") # 进一步获取跟标签下子标签的子标签
print(event_object.tag,event_object.attrib)
# 2.3 通过标签名称获取标签 findall()
events_objects = root.findall("Events") # 此种写法只能获取根标签下的一级子标签,即只能查询下一级标签,不能查询到下一级的下一级标签,但是可以获取下一级所有符合名称的标签
for event_clee in events_objects:
print(event_clee.tag, event_clee.attrib)
event_object = event_clee.findall("Event") # 进一步获取跟标签下子标签的子标签
for relation_cell in event_object:
print(relation_cell.tag, relation_cell.attrib)
# 2.4 findall(xpath)
Events_object = root.findall('.//Code')
Events_object1 = root.findall('.//Code[@curCode="010697059381010910N053000117230527"]')
Events_object2 = root.findall('.//*[@curCode="010697059381010910N053000117230527"]')
#注意 前面的“.”不能省略,
print(Events_object)
print(Events_object1)
print(Events_object2[0])
from xml.etree import ElementTree as ET
# 1、打开xml文件
tree =ET.parse(r"E:\Acctrue2.0Test\testData\N0530YPYM001.xml")
# 获xml文件的内容取根标签
root = tree.getroot()
print(root)
# 2.2 根据标签名全文搜索标签
Code_object = root.iter("Code") 全文搜索标签名为“Code”的标签
print(Code_object)
for code in Code_object:
print(code.tag, code.attrib)
from xml.etree import ElementTree as ET
tree =ET.parse(r"E:\Acctrue2.0Test\testData\N0530YPYM001.xml")
# 获xml文件的内容取根标签
root = tree.getroot()
relation_object = root.find("Events").find("Event").iter("Relation") # 获取第一个Events的一级子标签下的Relation子标签
for relation_cell in relation_object:
relation_cell.set("productCode", "产品编码") # 如果有相应属性,则修改属性值,没有则新增
relation_cell.set("productCode2", "产品编码2")
relation_cell.find("Batch").find("Code").text="追溯码" # 注意:如果之前是短标签,增加文本属性后自动变为长标签。
tree = ET.ElementTree(root)
tree.write("new.xml", encoding="utf-8",short_empty_elements=True) # 如果文件不存在,则创建文件,如果文件已存在则修改响应内容
from xml.etree import ElementTree as ET
tree =ET.parse(r"E:\Acctrue2.0Test\testData\N0530YPYM001.xml")
# 获xml文件的内容取根标签
root = tree.getroot()
# ####################错误的删除方式########################
# # 获取响应标签
# Event_object = root.find("Events").find("Event")
# # 删除相应标签
# root.remove(Event_object) # 删除只能删除其子标签,不能删除其子标签下的子标签,因为relation_object是子标签下的子标签,因此此时删除失败
################## 正确的删除方式#############################
Events_object = root.find("Events")
Event_object = Events_object.find("Event")
Events_object.remove(Event_object)
tree = ET.ElementTree(root)
tree.write("new.xml", encoding="utf-8") # 如果文件不存在,则创建文件,如果文件已存在则修改响应内容
方式1 (Element)
先创建各类标签,再建立标签之间关系
from xml.etree import ElementTree as ET
# 创建根标签
root = ET.Element("root")
# 创建一个标签tagName1
tagName1 = ET.Element("tagName1", {"tag1Attribute":"AttributeValue1"})
# 创建一个标签tagName2
tagName2 = ET.Element("tagName2", {"tag2Attribute":"AttributeValue2"})
# 创建一个标签tagName11
tagName11 = ET.Element("tagName11", {"tag11Attribute":"AttributeValue11"})
# 创建一个标签tagName12
tagName12 = ET.Element("tagName12", {"tag12Attribute":"AttributeValue12"})
# 将标签tagName11和tagName12 添加的tagName1中作为tagName1的子标签
tagName1.append(tagName11)
tagName1.append(tagName12)
# 将标签tagName1和tagName2 添加的root中作为root的子标签
root.append(tagName1)
root.append(tagName2)
# 保存
tree = ET.ElementTree(root)
tree.write("newCreate.xml", xml_declaration=True, encoding="utf-8",short_empty_elements=True)
# xml_declaration是否包含声明文件, encoding编码方式,short_empty_elements 规定是短标签(单标签)还是双标签
<?xml version='1.0' encoding='utf-8'?>
<root>
<tagName1 tag1Attribute="AttributeValue1">
<tagName11 tag11Attribute="AttributeValue11"/>
<tagName12 tag12Attribute="AttributeValue12"/>
</tagName1>
<tagName2 tag2Attribute="AttributeValue2"/>
</root>
方式2 (makeelement)
from xml.etree import ElementTree as ET
# 创建根节点
root = ET.Element("family")
# 创建一级子标签
son1 = root.makeelement("son", {"name":"son1"})
son2 = root.makeelement("son", {"name":"son2"})
# 创建二级子标签
grandson1 = son1.makeelement("grandson1", {"name":"grandson1"})
grandson2 = son1.makeelement("grandson1", {"name":"grandson2"})
# 将二级子标签与一级子标签关联
son1.append(grandson1)
son1.append(grandson2)
# 将一级子标签与根标签关联
root.append(son2)
root.append(son1)
tree = ET.ElementTree(root)
tree.write("../testData/neswfile.xml", xml_declaration=True, encoding="utf-8")
方式3
此种方式是在创建元素时直接建立相关关系:
from xml.etree import ElementTree as ET
# 创建根节点
root = ET.Element("family")
# 创建一级子标签
son1 = ET.SubElement(root, "son", {"name":"son1"})
son2 = ET.SubElement(root,"son", {"name":"son2"})
# 创建二级子标签
grandson1 = ET.SubElement(son1,"grandson1", {"name":"grandson1"})
grandson1.text="大孙子"
grandson2 = ET.SubElement(son1,"grandson1", {"name":"grandson2"})
grandson2.text="小孙子"
tree = ET.ElementTree(root)
tree.write("../testData/neswfile.xml", xml_declaration=True, encoding="utf-8")
<?xml version='1.0' encoding='utf-8'?>
<family>
<son name="son1">
<grandson1 name="grandson1">大孙子</grandson1>
<grandson1 name="grandson2">小孙子</grandson1>
</son>
<son name="son2"/>
</family>