【问题标题】:Python -parse xml with variable nested elements into csvPython - 将带有可变嵌套元素的 xml 解析为 csv
【发布时间】:2018-04-08 16:01:00
【问题描述】:

迫切需要帮助。我是 Python 的初学者,并且尝试了几天(和几夜)来做到这一点,但没有成功。拥有大型 xml 文件,其中包含具有可变子子元素(即属性值)的子元素(即属性)的元素(即帐户)。由于子子元素是可变的,我不知道如何让它深入到它需要拾取所有内容并将其放入.csv 中。 因此,每个帐户可能有很多记录。我想要一行包含帐户 ID,后跟属性名称,然后是属性值。如果一个帐户有很多属性,他们可以有很多行。

非常感谢您提供的任何帮助! :)

<?xml version="1.0" encoding="UTF-8"?>
<rbacx>
  <namespace namespaceName="ABC RSS : xxxxxxx" namespaceShortName="RSS" />
  <attributeValues />
  <accounts>
    <account id="AAGALY2">
      <name>AAGALY2</name>
      <endPoint>ABCD</endPoint>
      <domain>ABCD</domain>
      <comments />
      <attributes>  ### one account can have many attribute records
        <attribute name="appUserName">
          <attributeValues>
            <attributeValue>
              <value><![CDATA[A, Agglya]]></value>
            </attributeValue>
          </attributeValues>
        </attribute>
        <attribute name="costCentre">
          <attributeValues>
            <attributeValue>
              <value><![CDATA[6734]]></value>
            </attributeValue>
          </attributeValues>
        </attribute>
        <attribute name="App ID">
          <attributeValues>
            <attributeValue>
              <value><![CDATA[AAGALY2]]></value>
            </attributeValue>
          </attributeValues>
        </attribute>
        <attribute name="Last Access Date">
          <attributeValues>
            <attributeValue>
              <value><![CDATA[00000000]]></value>

etc......

希望 csv 看起来像这样:

AcctName   Endpoint     Domain     AttribName     AttribValue
AAGALY2     ABCD        ABCD       appUserName    A, Agalya
AAGALY2     ABCD        ABCD       CostCentre     333333
AAGALY2     ABCD        ABCD       App ID         AAGALY2
AAGALY2     ABCD        ABCD       Jobtemplate    A12-can read
JSMITH1     EFG         ABCD       appUserName    J, Smith
JSMITH1     ABCD        ABCD       CostCentre     12345
JSMITH1     ABCD        ABCD       Jobtemplate    A22-perm to write
ZZMITH3     EFG         GHI        appUserName    Z, Zmith
ZZMITH3     EFG         GHI        CostCentre     3456

【问题讨论】:

标签: python xml-parsing


【解决方案1】:

如果 xml etree 没有帮助,我发现 xmltodict 是一种非常简单的方法来通过 xml 解析。

那么你的代码可能是什么样子的:

import xmltodict
import csv

xmldict = xmltodict.parse(yourxml)

f = csv.writer(open('yourcsv.csv', "w"))

#write field names to file keys of the dict, or you can specify the ones you outlined in your output eg.
f.writerow(xmldict.keys())

#write the contents
for key in xmldict:
    f.writerow(key['attrs'], key['attrs'] etc. etc.)

显然,您必须根据 xml 的嵌套进行映射并访问所需的“属性”,但通过 dict 结构应该非常直接。希望这会有所帮助!

【讨论】:

  • 我尝试了代码,但无法安装 xmltodict。不断收到错误消息。经过更多研究,发现“getiterate()”效果很好。它贯穿整个结构。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 2022-01-17
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多