python xml 解析,使用Python将XML解析为表格

I'm trying to parse XML to table-like structure in Python.

Imagine XML like this:

element 1

element 2

subElement 3

I'd like to have result like this:

KEY | VALUE

base.element1 | "element 1"

base.element2 | "element 2"

base.element3.subElement3 | "subElement 3"

I've tried using xml.etree.cElementTree, then functions described here How to convert an xml string to a dictionary in Python?

Is there any function that can do this? All answers I found are written for particular XML schemes and would need to be edited for each new XML scheme.

For reference, in R it's easy with XML and XML2 packages and xmlToList function.

解决方案

I've got the needed outcome using following script.

XML File:

element 1

element 2

subElement 3

Python code:

import pandas as pd

from lxml import etree

data = "C:/Path/test.xml"

tree = etree.parse(data)

lstKey = []

lstValue = []

for p in tree.iter() :

lstKey.append(tree.getpath(p).replace("/",".")[1:])

lstValue.append(p.text)

df = pd.DataFrame({'key' : lstKey, 'value' : lstValue})

df.sort_values('key')

Result:

8774056cd502bfd1705c766b0668d5d0.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值