簡體   English   中英

Python-將具有可變嵌套元素的xml解析到csv中

[英]Python -parse xml with variable nested elements into csv

迫切需要幫助。 我是Python的初學者,已經嘗試了數天(和數夜)來做到這一點,但沒有成功。 具有較大的xml文件,該文件具有的元素(即帳戶)具有帶有可變子子元素(即attributeValue)的子元素(即屬性)。 由於sub-sub-element是可變的,因此我不知道如何將其細分為需要提取的所有內容並將其放入.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

如果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結構應該很簡單。 希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM