首页 > 解决方案 > 将 XML 属性检索到 DataFrame

问题描述

我的 XML 如下所示:

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<foo bar1="1" bar2="2" bar3="23" bar4="4">
    <baz abc1="xxx" abc2="yyy">
        <item1 a="0" b="123"/>
        <item2 a="0" b="124"/>
        <item3>blue</item3>
        <item4>green</item4>
        <item5>yellow</item5>
        <item6>red</item6>
        <item7>white</item7>

我能够检索 , 等中包含的项目item1item2现在我想检索 or 中包含的属性foo, bazlike bar1or abc1

一切都将发送到 pandas DataFrame。代码如下。请注意,col1并且col2正在返回None

from lxml import objectify
import pandas as pd

xml = objectify.parse('file.xml')
root = xml.getroot()

data = []

for i in range(len(root.getchildren())):
    data.append([child.text for child in root.getchildren()[i].getchildren()])

df = pd.DataFrame(data)
df.columns = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7']

df.head()

   item1  item2 item3     item4    item5   item6   item7
0  None    None   blue    green   yellow    red    white
1  None    None   blue    green   yellow    red    white
2  None    None   blue    green   yellow    red    white
3  None    None   blue    green   yellow    red    white
4  None    None   blue    green   yellow    red    white

我怎样才能获得这些属性?提前致谢。

标签: pythonpandaslxml

解决方案


推荐阅读