在Python中处理XML数据时,遍历所有节点和属性是获取完整数据信息的常见需求,使用标准库自带的xml.etree.ElementTree模块就能高效完成这个操作,不需要额外安装第三方依赖。

准备工作
首先我们需要导入对应的模块,同时准备一份测试用的XML数据,方便后续演示遍历逻辑。测试XML内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="编程" id="1">
<title>Python基础教程</title>
<author>张三</author>
<price>59.9</price>
</book>
<book category="文学" id="2">
<title>散文精选</title>
<author>李四</author>
<price>39.9</price>
</book>
</bookstore>
遍历XML所有节点的方法
ElementTree模块提供了iter()方法,这个方法可以递归遍历XML树中的所有节点,不需要我们手动写递归逻辑,使用起来非常方便。
基础节点遍历示例
下面的代码演示了如何遍历所有节点并打印节点名称和文本内容:
import xml.etree.ElementTree as ET
# 解析XML内容,这里直接使用上面的测试XML字符串
xml_data = """<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="编程" id="1">
<title>Python基础教程</title>
<author>张三</author>
<price>59.9</price>
</book>
<book category="文学" id="2">
<title>散文精选</title>
<author>李四</author>
<price>39.9</price>
</book>
</bookstore>"""
# 从字符串解析XML
root = ET.fromstring(xml_data)
# 使用iter方法遍历所有节点
for node in root.iter():
print(f"节点名称:{node.tag}")
# 如果节点有文本内容且不是空白字符,打印文本内容
if node.text and node.text.strip():
print(f"节点文本:{node.text.strip()}")
print("-" * 20)
指定节点类型遍历
如果只需要遍历某一种特定名称的节点,可以给iter()方法传入节点名称作为参数,这样只会返回对应名称的节点:
import xml.etree.ElementTree as ET
xml_data = """<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="编程" id="1">
<title>Python基础教程</title>
<author>张三</author>
<price>59.9</price>
</book>
<book category="文学" id="2">
<title>散文精选</title>
<author>李四</author>
<price>39.9</price>
</book>
</bookstore>"""
root = ET.fromstring(xml_data)
# 只遍历book节点
for book_node in root.iter("book"):
print(f"找到book节点,category属性:{book_node.get('category')}")
print("-" * 20)
遍历XML所有属性的方法
每个节点对象的attrib属性是一个字典,存储了当前节点的所有属性键值对,我们可以通过遍历这个字典来获取所有属性信息。
遍历单个节点的所有属性
下面的代码演示了如何获取指定节点的所有属性:
import xml.etree.ElementTree as ET
xml_data = """<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="编程" id="1">
<title>Python基础教程</title>
<author>张三</author>
<price>59.9</price>
</book>
</bookstore>"""
root = ET.fromstring(xml_data)
# 获取第一个book节点
book_node = root.find("book")
# 遍历book节点的所有属性
for attr_name, attr_value in book_node.attrib.items():
print(f"属性名:{attr_name},属性值:{attr_value}")
遍历所有节点的所有属性
结合节点遍历和属性遍历的逻辑,就可以实现遍历XML中所有节点的所有属性:
import xml.etree.ElementTree as ET
xml_data = """<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="编程" id="1">
<title>Python基础教程</title>
<author>张三</author>
<price>59.9</price>
</book>
<book category="文学" id="2">
<title>散文精选</title>
<author>李四</author>
<price>39.9</price>
</book>
</bookstore>"""
root = ET.fromstring(xml_data)
# 遍历所有节点
for node in root.iter():
# 如果节点有属性,打印属性信息
if node.attrib:
print(f"节点{node.tag}的属性:")
for attr_name, attr_value in node.attrib.items():
print(f" {attr_name}: {attr_value}")
print("-" * 20)
完整遍历节点和属性的综合示例
下面的代码把节点遍历和属性遍历结合起来,一次性输出XML中所有节点的名称、文本内容以及对应的属性信息:
import xml.etree.ElementTree as ET
xml_data = """<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="编程" id="1">
<title>Python基础教程</title>
<author>张三</author>
<price>59.9</price>
</book>
<book category="文学" id="2">
<title>散文精选</title>
<author>李四</author>
<price>39.9</price>
</book>
</bookstore>"""
root = ET.fromstring(xml_data)
for node in root.iter():
print(f"节点名称:{node.tag}")
# 打印节点属性
if node.attrib:
print("节点属性:")
for k, v in node.attrib.items():
print(f" {k}: {v}")
# 打印节点文本
if node.text and node.text.strip():
print(f"节点文本:{node.text.strip()}")
print("=" * 30)
注意事项
- 如果XML数据存储在文件中,可以使用
ET.parse("文件路径")方法解析,然后通过getroot()获取根节点,后续遍历逻辑和字符串解析的方式一致。 - 节点的
text属性返回的是节点标签之间的文本内容,如果标签之间有换行或者空格,可能需要用strip()方法处理后再使用。 - 如果XML结构非常复杂,包含命名空间,遍历的时候需要注意节点名称会包含命名空间前缀,需要对应处理才能正确匹配节点名称。
PythonXML遍历节点遍历属性ElementTree修改时间:2026-07-20 18:00:39