python - 将复杂的 XML 文件转换为 Pandas 数据框/CSV - Python
问题描述
我目前正在将复杂的 XML 文件转换为 csv 或 pandas df。我对 xml 数据格式的经验为零,我在网上找到的所有代码建议都不适合我。任何人都可以帮我解决这个问题吗?
数据中有很多我不需要的元素,所以我不会在此处包含这些元素。
出于隐私原因,我不会在这里上传原始数据,但我会分享结构的样子。
<RefData>
<Attributes>
<Id>1011</Id>
<FullName>xxxx</FullName>
<ShortName>xx</ShortName>
<Country>UK</Country>
<Currency>GBP</Currency>
</Attributes>
<PolicyID>000</PolicyID>
<TradeDetails>
<UniqueTradeId>000</UniqueTradeId>
<Booking>UK</Booking>
<Date>12/2/2019</Date>
</TradeDetails>
</RefData>
<RefData>
<Attributes>
<Id>1012</Id>
<FullName>xxx2</FullName>
<ShortName>x2</ShortName>
<Country>UK</Country>
<Currency>GBP</Currency>
</Attributes>
<PolicyID>002</PolicyID>
<TradeDetails>
<UniqueTradeId>0022</UniqueTradeId>
<Booking>UK</Booking>
<Date>12/3/2019</Date>
</TradeDetails>
</RefData>
我需要标签中的所有内容。
理想情况下,我希望标题和输出如下所示:
我真诚地感谢我能得到的任何帮助。谢谢一米。
解决方案
关于您的输入 XML 文件的一个更正:它必须包含一个主要元素(任何名称),并且在其中包含您的RefData 元素。
所以输入文件实际上包含:
<Main>
<RefData>
...
</RefData>
<RefData>
...
</RefData>
</Main>
要处理输入的 XML 文件,您可以使用lxml包,因此要从以下位置导入它:
from lxml import etree as et
然后我注意到您实际上不需要整个解析的 XML 树,因此通常应用的方案是:
- 解析后立即读取每个元素的内容,
- 将任何子元素的内容(文本)保存在任何中间数据结构中(我选择了字典列表),
- 删除源 XML 元素(不再需要),
- 在读取循环之后,从上述中间数据结构创建结果 DataFrame。
所以我的代码如下所示:
rows = []
for _, elem in et.iterparse('RefData.xml', tag='RefData'):
rows.append({'id': elem.findtext('Attributes/Id'),
'fullname': elem.findtext('Attributes/FullName'),
'shortname': elem.findtext('Attributes/ShortName'),
'country': elem.findtext('Attributes/Country'),
'currency': elem.findtext('Attributes/Currency'),
'Policy ID': elem.findtext('PolicyID'),
'UniqueTradeId': elem.findtext('TradeDetails/UniqueTradeId'),
'Booking': elem.findtext('TradeDetails/Booking'),
'Date': elem.findtext('TradeDetails/Date')
})
elem.clear()
elem.getparent().remove(elem)
df = pd.DataFrame(rows)
要全面了解详细信息,请在 Web 上搜索lxml的描述和使用的每种方法。
对于您的样本数据,结果是:
id fullname shortname country currency Policy ID UniqueTradeId Booking Date
0 1011 xxxx xx UK GBP 000 000 UK 12/2/2019
1 1012 xxx2 x2 UK GBP 002 0022 UK 12/3/2019
可能要执行的最后一步是将上述 DataFrame 保存在 CSV 文件中,但我想您知道该怎么做。
推荐阅读
- java - 尝试使用 parseInt() 和 trim() 时出现 NumberFormatException 无法修复它
- docker - Podman(码头工人)容器
- django - “包”对象没有属性“评论”
- intellij-idea - 在 IntelliJ 中创建 Web 项目时未显示设置中的目录
- swift - 使 CLLocationCoordinate2D Equatable 打破 SwiftUI 地图
- php - mysql中的php循环ajax数组
- java - Oauth2 Spring-boot只读连接错误
- google-compute-engine - Google App Engine 不应该比 Google Kubernetes 引擎贵吗
- html - 导航时 HTML 网站 url 包含 /#[object Object]
- bash - 将不同路径的所有文件名及其在 Unix 中的时间间隔关联起来