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

使用Python提取XML实体及对应属性并转换为表格

XML实体与属性提取方案

问题描述

需要从自定义XML文件中提取28个实体(对应数据表)及其属性(对应数据列),转换为表格格式。XML示例片段如下:

<ESpace Key="ESpace:y7vmLUGpAMoLhw4MvpnAPg" Name="Onboarding_Core" UserProviderEspace="Users" DefaultThemeNewRuntime="ThemeReference:rQ3WUJw0o0+BC9ZDjXD7uA" DefaultTransition="Fade" UseCookies="Yes" WebScreenRenderingMode="HTML5" ModuleType="CrossDevice">
<Actions>
</Actions>
<Entities>
<Entity Key="Entity:X2oBACCeRUeSQxJFoyn1hA" ExposeReadOnly="Yes" Identifier="Attribute:_EXIewz0o024UgjslFt7_g" Public="Yes" Name="Document">
<Attributes>
<Attribute Key="Attribute:_EXIewz0o024UgjslFt7_g" IsMandatory="Yes" Name="Id" DataType="Long Integer" IsAutoNumber="Yes"/>
<Attribute Key="Attribute:ypRA49SJBkexc+ICR12zdw" Length="50" Name="Name" DataType="Text"/>
<Attribute Key="Attribute:mdWB6OaTkE26BwxQRRfbBg" Name="CreatedOn" DataType="Date Time"/>
<Attribute Key="Attribute:W0foZDFa5kme6QySnTNEMA" Name="Binary" DataType="Binary Data"/>
</Attributes>
</Entity>
<Entity Key="Entity:6NuECH7xe06M250tQsPsJA" IsStaticEntity="Yes" IsMultitenant="No" ExposeReadOnly="Yes" Identifier="Attribute:jBExnTjCy0GOtV5fZZG0pw" Public="Yes" Name="DateFormat" Folder="Folder:SErnhCWKOUKpp39VDQVVcg">
<Attributes>
<Attribute Key="Attribute:jBExnTjCy0GOtV5fZZG0pw" IsMandatory="Yes" Name="Id" DataType="Integer" IsAutoNumber="Yes" DeleteRule="Ignore"/>
<Attribute Key="Attribute:Q0S8yDbafEi+YMF0rXnbvg" IsMandatory="Yes" Length="50" Name="Format" DataType="Text" DeleteRule="Ignore"/>
<Attribute Key="Attribute:XUw_zMWoZki2qWuZcYRizw" IsMandatory="Yes" Length="50" Name="Example" DataType="Text" DeleteRule="Ignore"/>
<Attribute Key="Attribute:YpcYFT5YNUKxqaYLZOe6qA" IsMandatory="Yes" Name="Order" DataType="Integer" DeleteRule="Ignore"/>
<Attribute Key="Attribute:3QRHk0Wl7kuwg4gmzIs8yw" IsMandatory="Yes" Name="IsActive" DataType="Boolean" DeleteRule="Ignore"/>
</Attributes>
</Entity>
</Entities>
</ESpace>

尝试的代码存在问题:root.findall('.//Attribute')会全局查找所有属性,无法关联到当前遍历的实体,导致属性和实体不匹配。代码片段如下:

table_list=[]
Attribute_list=[]
for entity_list in root.findall('.//Entity'):
    entity_dict={}
    entity_dict['Entity_Name']=entity_list.get('Name')
    print(entity_dict)
    for attribute_list in root.findall('.//Attribute'):
        attribute_dict={}
        attribute_dict['Attribute_Name']=attribute_list.get('Name')
        for child_elem_1 in attribute_list:
            attribute_dict[child_elem_1.tag]=child_elem_1.text
        Attribute_list.append(attribute_dict)
    print(Attribute_list)
df= pd.DataFrame(Attribute_list)
print(df.head(10))

错误分析

核心问题是属性查找的上下文错误:使用root.findall会从XML根节点开始全局搜索,而不是在当前entity_list的范围内查找。需要将属性查找的范围限定在当前实体节点内部。

修正后的代码

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

# 解析XML文件(替换为你的XML文件路径)
tree = ET.parse('your_xml_file.xml')
root = tree.getroot()

# 存储最终数据的列表
data_list = []

# 遍历每个实体
for entity in root.findall('.//Entity'):
    entity_name = entity.get('Name')
    # 在当前实体下查找所有属性(限定在当前实体的Attributes节点内)
    attributes = entity.find('.//Attributes').findall('Attribute')
    # 遍历每个属性,收集信息并关联实体名
    for attr in attributes:
        attr_dict = {
            'Entity_Name': entity_name,
            'Attribute_Name': attr.get('Name'),
            'DataType': attr.get('DataType'),
            'IsMandatory': attr.get('IsMandatory'),
            'Length': attr.get('Length'),
            'IsAutoNumber': attr.get('IsAutoNumber'),
            'DeleteRule': attr.get('DeleteRule')
        }
        # 可以根据需要添加更多属性字段
        data_list.append(attr_dict)

# 转换为DataFrame
df = pd.DataFrame(data_list)
# 打印结果(或保存为Excel/CVS)
print(df)

关键说明

  1. 限定查找范围:使用entity.find('.//Attributes').findall('Attribute')替代全局查找,确保只获取当前实体下的属性。
  2. 关联实体与属性:每个属性字典中加入Entity_Name字段,保证实体和属性的对应关系。
  3. 字段按需扩展:代码中列出了常见属性字段,可根据XML中实际存在的属性(如Key)自行添加。

示例输出表格

Entity_NameAttribute_NameDataTypeIsMandatoryLengthIsAutoNumberDeleteRule
DocumentIdLong IntegerYesNaNYesNaN
DocumentNameTextNaN50NaNNaN
DocumentCreatedOnDate TimeNaNNaNNaNNaN
DocumentBinaryBinary DataNaNNaNNaNNaN
DateFormatIdIntegerYesNaNYesIgnore
DateFormatFormatTextYes50NaNIgnore
DateFormatExampleTextYes50NaNIgnore
DateFormatOrderIntegerYesNaNNaNIgnore
DateFormatIsActiveBooleanYesNaNNaNIgnore

内容的提问来源于stack exchange,提问作者Sam Amre

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:53:14