使用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)
关键说明
- 限定查找范围:使用
entity.find('.//Attributes').findall('Attribute')替代全局查找,确保只获取当前实体下的属性。 - 关联实体与属性:每个属性字典中加入
Entity_Name字段,保证实体和属性的对应关系。 - 字段按需扩展:代码中列出了常见属性字段,可根据XML中实际存在的属性(如
Key)自行添加。
示例输出表格
| Entity_Name | Attribute_Name | DataType | IsMandatory | Length | IsAutoNumber | DeleteRule |
|---|---|---|---|---|---|---|
| Document | Id | Long Integer | Yes | NaN | Yes | NaN |
| Document | Name | Text | NaN | 50 | NaN | NaN |
| Document | CreatedOn | Date Time | NaN | NaN | NaN | NaN |
| Document | Binary | Binary Data | NaN | NaN | NaN | NaN |
| DateFormat | Id | Integer | Yes | NaN | Yes | Ignore |
| DateFormat | Format | Text | Yes | 50 | NaN | Ignore |
| DateFormat | Example | Text | Yes | 50 | NaN | Ignore |
| DateFormat | Order | Integer | Yes | NaN | NaN | Ignore |
| DateFormat | IsActive | Boolean | Yes | NaN | NaN | Ignore |
内容的提问来源于stack exchange,提问作者Sam Amre
相关产品推荐
相关产品推荐

