import xml.etree.ElementTree as ET
# 示例 XML 字符串
xml_data = """
<root>
<parent>
<child1>Value 1</child1>
<child2>Value 2</child2>
<nested>
<subchild1>Sub Value 1</subchild1>
<subchild2>Sub Value 2</subchild2>
</nested>
</parent>
<parent>
<child1>Value 3</child1>
<child2>Value 4</child2>
<nested>
<subchild1>Sub Value 3</subchild1>
<subchild2>Sub Value 4</subchild2>
</nested>
</parent>
</root>
"""
# 解析 XML 数据
root = ET.fromstring(xml_data)
# 遍历多层节点
for parent in root.findall('parent'):
child1 = parent.find('child1').text
child2 = parent.find('child2').text
print(f'Child1: {child1}, Child2: {child2}')
# 访问嵌套的子节点
nested = parent.find('nested')
subchild1 = nested.find('subchild1').text
subchild2 = nested.find('subchild2').text
print(f'Subchild1: {subchild1}, Subchild2: {subchild2}')
xml.etree.ElementTree 模块来解析 XML。ET.fromstring() 方法将 XML 字符串解析为一个 ElementTree 对象。findall() 方法查找所有 parent 节点。find() 方法查找每个 parent 节点下的 child1 和 child2 子节点,并获取它们的文本内容。nested 节点,获取其下的 subchild1 和 subchild2 子节点的文本内容。parent 节点及其嵌套子节点的内容。这段代码展示了如何解析包含多层节点的 XML,并逐层访问和提取所需的数据。
下一篇:python opencv教程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站