在Python中将多个嵌套XML解析为Pandas数据帧表

2024-09-30 14:18:44 发布

您现在位置:Python中文网/ 问答频道 /正文

<?xml version='1.0' encoding='UTF-8' ?>
  <DOC>
    <INFO1
      A = "1"
      B = "2"
      C = "3"
    >
      <INFO12
        D = "a"
      >
      </INFO12>
    </INFO1>
    <INFO2
      E = "4"
      F = "5"
      G = "6"
    >
      <INFO21
        H = "b"
      >
      </INFO21>
    </INFO2>
 </DOC>
TestFile="test.xml"
ttree = etree.parse(TestFile)
troot = ttree.getroot()
df_cols =["Col1", "Col2", "Col3", "Col4","Col5","Col6"
              "Col7", "Col8"]
df = pd.DataFrame(columns =df_cols)

for i in troot: 
    df = df.append(pd.Series([i.get('A'), i.get('B'),i.get('C'), i.get('D'),
                                     i.get('E'), i.get('F'),i.get('G'),i.get('H')],
                          index = df_cols), ignore_index=True)
        
df.head()

https://i.stack.imgur.com/pvBnm.png

问:我正试图使用XML.etree.cElementTree库将XML解析为Python中的数据帧。但是如何在一行中生成结果,包括a和b,因此将是“1,2,3,a,4,5,6,b”。 谢谢大家!


Tags: dfgetindexdocxmlpdetreecols
1条回答
网友
1楼 · 发布于 2024-09-30 14:18:44

你能使用其他图书馆吗

from simplified_scrapy import SimplifiedDoc

html = '''
<?xml version='1.0' encoding='UTF-8' ?>
  <DOC>
    <INFO1
      A = "1"
      B = "2"
      C = "3"
    >
      <INFO12
        D = "a"
      >
      </INFO12>
    </INFO1>
    <INFO2
      E = "4"
      F = "5"
      G = "6"
    >
      <INFO21
        H = "b"
      >
      </INFO21>
    </INFO2>
 </DOC>
'''
doc = SimplifiedDoc(html)
infos = doc.DOC.children
row = [infos[0].A,infos[0].B,infos[0].C,infos[0].child.D,
    infos[1].E,infos[1].F,infos[1].G,infos[1].child.H]
print (row)

结果:

['1', '2', '3', 'a', '4', '5', '6', 'b']

相关问题 更多 >