以下是一个使用Python解析XML并遍历元素节点的示例代码:
import xml.dom.minidom
# 加载XML文件
dom = xml.dom.minidom.parse("example.xml")
# 获取根元素节点
root = dom.documentElement
# 遍历所有元素节点
def traverse_elements(node):
if node.nodeType == node.ELEMENT_NODE:
print("Element Node: " + node.nodeName)
# 打印元素节点的属性
if node.hasAttributes():
attributes = node.attributes
for i in range(attributes.length):
attribute = attributes.item(i)
print("Attribute: " + attribute.nodeName + " = " + attribute.nodeValue)
# 打印元素节点的文本内容
if node.firstChild.nodeType == node.TEXT_NODE:
print("Text Content: " + node.firstChild.nodeValue)
# 递归遍历子节点
for child in node.childNodes:
traverse_elements(child)
# 开始遍历
traverse_elements(root)
假设XML文件example.xml
的内容如下:
John
New York
Jane
London
运行上述代码将输出:
Element Node: person
Attribute: age = 20
Element Node: name
Text Content: John
Element Node: city
Text Content: New York
Element Node: person
Attribute: age = 25
Element Node: name
Text Content: Jane
Element Node: city
Text Content: London
上一篇:遍历XML