【发布时间】:2021-04-07 13:18:24
【问题描述】:
我想要展平多个 XML 文件,我正在寻找将 xml 转换为平面文件的通用函数或逻辑。大多数答案都包含硬编码标签。最接近的是Python : Flatten xml to csv with parent tag repeated in child,但仍然有硬编码的解决方案。 对于下面的输入 xml
<root>
<child> child-val </child>
<child2> child2-val2 </child2>
<anotherchild>
<childid> another child 45</childid>
<childname> another child name </childname>
</anotherchild>
<group>
<groupid> groupid-123</groupid>
<grouplist>
<groupzone>
<groupname>first </groupname>
<groupsize> 4</groupsize>
</groupzone>
<groupzone>
<groupname>second </groupname>
<groupsize> 6</groupsize>
</groupzone>
<groupzone>
<groupname> third </groupname>
<groupsize> 8 </groupsize>
</groupzone>
</grouplist>
</group>
<secondgroup>
<secondgroupid> secondgroupid-42 </secondgroupid>
<secondgrouptitle> second group title </secondgrouptitle>
<secondgrouplist>
<secondgroupzone>
<secondgroupsub>
<secondsub>v1</secondsub>
<secondsubid>12</secondsubid>
</secondgroupsub>
<secondgroupname> third </secondgroupname>
<secondgroupsize> 4</secondgroupsize>
</secondgroupzone>
<secondgroupzone>
<secondgroupsub>
<secondsub>v2</secondsub>
<secondsubid>1</secondsubid>
</secondgroupsub>
<secondgroupname>fourth </secondgroupname>
<secondgroupsize> 6</secondgroupsize>
</secondgroupzone>
<secondgroupzone>
<secondgroupsub>
<secondsub>v3</secondsub>
<secondsubid>45</secondsubid>
</secondgroupsub>
<secondgroupname> tenth </secondgroupname>
<secondgroupsize> 10 </secondgroupsize>
</secondgroupzone>
</secondgrouplist>
</secondgroup>
<child3> val3 </child3>
</root>
我尝试使用这个包pandas-read-xml 获得了大部分值,但是另一个子标签值显示在一个列(另一个子项)中,而不是另一个子项|childid 和另一个子项|另一个子项。如果可能,建议使用通用逻辑将 xml 转换为平面文件。
import pandas_read_xml as pdx
df = pdx.read_xml(xml_content, ['root'])
fully_fatten_df = pdx.fully_flatten(df)
fully_fatten_df.to_csv("stack.csv", index=False)
输出 csv
anotherchild,child,child2,child3,group|groupzone|groupname,group|groupzone|groupsize,secondgroup|secondgroupzone|secondgroupname,secondgroup|secondgroupzone|secondgroupsize,secondgroup|secondgroupzone|secondgroupsub|secondsub,secondgroup|secondgroupzone|secondgroupsub|secondsubid
,child-val,child2-val2,val3,,,third,4,v1,12
,child-val,child2-val2,val3,,,fourth,6,v2,1
,child-val,child2-val2,val3,,,tenth,10,v3,45
,child-val,child2-val2,val3,first,4,,,,
,child-val,child2-val2,val3,second,6,,,,
,child-val,child2-val2,val3,third,8,,,,
another child 45,child-val,child2-val2,val3,,,,,,
another child name,child-val,child2-val2,val3,,,,,,
,child-val,child2-val2,val3,,,,,,
,child-val,child2-val2,val3,,,,,,
,child-val,child2-val2,val3,,,,,,
【问题讨论】:
-
请发布您预期的输出数据框。此外,您可以使用 python 的 lxml 模块或 ET 模块
-
Output csv是您提供的代码的结果吗?如果是这样 - 你能显示你想要的确切输出 csv 吗?
标签: python-3.x xml pandas logic