Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python解析xml多层节点

作者:飒舛流寒   发布日期:2026-03-16   浏览:104

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}')

解释说明:

  1. 导入模块:使用 xml.etree.ElementTree 模块来解析 XML。
  2. 示例 XML 字符串:定义了一个包含多层节点的 XML 字符串,用于演示如何解析。
  3. 解析 XML:使用 ET.fromstring() 方法将 XML 字符串解析为一个 ElementTree 对象。
  4. 遍历多层节点
    • 使用 findall() 方法查找所有 parent 节点。
    • 使用 find() 方法查找每个 parent 节点下的 child1child2 子节点,并获取它们的文本内容。
    • 继续访问嵌套的 nested 节点,获取其下的 subchild1subchild2 子节点的文本内容。
  5. 输出结果:打印每个 parent 节点及其嵌套子节点的内容。

这段代码展示了如何解析包含多层节点的 XML,并逐层访问和提取所需的数据。

上一篇:python tkinter button

下一篇:python opencv教程

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站