You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python提取XML标签路径及值并导出至Excel?

Python提取XML标签路径及值并导出至Excel

所需依赖

先安装必要的第三方库:

pip install pandas openpyxl

完整实现代码

import xml.etree.ElementTree as ET
import pandas as pd

def get_element_path(element):
    """递归获取元素的完整路径"""
    path = [element.tag]
    parent = element.parent
    while parent is not None:
        path.insert(0, parent.tag)
        parent = parent.parent
    return "/" + "/".join(path)

def parse_xml_to_data(xml_content):
    """解析XML,提取每个条目(如country)的标签路径和对应值"""
    root = ET.fromstring(xml_content)
    # 给每个元素添加parent属性,方便后续路径生成
    for parent in root.iter():
        for child in parent:
            child.parent = parent
    
    # 找到所有顶级条目节点(这里是所有<country>节点)
    items = root.findall(".//country")
    data_list = []
    
    for item in items:
        item_data = {}
        # 遍历当前条目下的所有叶子节点(无子节点的元素)
        for elem in item.iter():
            if len(elem) == 0:  # 叶子节点才有值
                path = get_element_path(elem)
                item_data[path] = elem.text.strip() if elem.text else ""
        data_list.append(item_data)
    
    return data_list

def export_to_excel(data, output_file):
    """将数据导出到Excel"""
    df = pd.DataFrame(data)
    df.to_excel(output_file, index=False)

# 示例XML内容(也可以替换为读取文件:ET.parse("input.xml").getroot())
sample_xml = """
<world>
<countries>
    <country>
        <name>a</name>
        <description>a short description</description>
        <population>
            <now>250000</now>
            <2000>100000</2000>
        </population>
    </country>
    <country>
        <name>b</name>
        <description>b short description</description>
        <population>
            <now>350000</now>
            <2000>150000</2000>
        </population>
    </country>
</countries>
</world>
"""

# 执行流程
if __name__ == "__main__":
    parsed_data = parse_xml_to_data(sample_xml)
    export_to_excel(parsed_data, "output.xlsx")
    print("Excel导出完成,文件名为output.xlsx")

代码说明

  1. 路径生成:get_element_path函数通过递归遍历父节点,拼接出每个元素的完整绝对路径(如/world/countries/country/population/now)
  2. XML解析:parse_xml_to_data函数先给所有元素添加父节点引用,然后定位到每个country条目,遍历其下所有叶子节点,收集路径和对应值
  3. Excel导出:用pandas将收集到的字典列表转为DataFrame,直接导出为Excel文件,自动将路径作为列名,每个条目对应一行数据

输出效果

导出的Excel文件中,列名是各个标签的完整路径,每行对应一个country的所有数据:

  • 第一列:/world/countries/country/name,对应值为a、b
  • 第二列:/world/countries/country/description,对应值为a short description、b short description
  • 后续列依次为/world/countries/country/population/now、/world/countries/country/population/2000,对应各自的数值

内容的提问来源于stack exchange,提问作者Sarang Gokte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:31:02