将嵌套的XML解析为DataFrame

时间:2019-10-15 18:16:11

标签: python xml pandas dataframe xml-parsing

我从XML形式的API中获得了响应。看起来像:

<result_set>
    <status> ...
    </status>
    <copyright> ...
    </copyright>
    <results>
       <congress> ...
       </congress>
       <chamber> ...
       </chamber>
       <num_results> ...
       </num_results>
       <offset> ...
       </offset>
       <members>
         <member>
           <id> ... </id>
           <name> ... </name>
           ...
           ...
           ...
         </member>
         <member> ... </member>
         ...
         ... 
         ...
       </members>
    </results>
</result_set>

我需要将每个标签下的数据转换成以下形式的pandas数据框:

id name ... ... ...
1  JOHN ... ... ...
2  DOE  ... ... ...

我已经尝试了ElementTree,但到目前为止所有尝试都失败了。

1 个答案:

答案 0 :(得分:1)

下面

import pandas as pd
import xml.etree.ElementTree as ET

xml = '''<r> 
         <members>
         <member>
           <id>1</id>
           <name>jack</name>
         </member>
         <member>
           <id>5</id>
           <name>dan</name>
         </member>

       </members>
       </r>'''

root = ET.fromstring(xml)
data = []
members = root.findall('.//member')
for member in members:
    data.append({c.tag:c.text for c in list(member)})
df = pd.DataFrame(data)
print(df.head())

输出

  id  name
0  1  jack
1  5   dan