首页 > 解决方案 > 将复杂的 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>

我需要标签中的所有内容。

理想情况下,我希望标题和输出如下所示:

在此处输入图像描述

我真诚地感谢我能得到的任何帮助。谢谢一米。

标签: pythonxmlpandas

解决方案


关于您的输入 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 文件中,但我想您知道该怎么做。


推荐阅读