[英]Using Python to get XML values and tags
我有一个 XML,它的一部分看起来像这样:
<?xml version="1.0" encoding="UTF-8" ?>,
<Settings>,
<System>,
<Format>Percent</Format>,
<Time>12 Hour Format</Time>,
<Set>Standard</Set>,
</System>,
<System>,
<Format>Percent</Format>,
<Time>12 Hour Format</Time>,
<Set>Standard</Set>,
<Alarm>ON</Alarm>,
<Haptic>ON</Haptic>'
</System>
</Settings>
我想要做的是使用 xpath 指定路径//Settings/System
并获取//Settings/System
的标签和值,以便我可以使用以下输出填充数据帧:
| Format | Time| Set| Alarm| Haptic|
|:_______|:____|:___|______|_______|
| Percent| 12 Hour Format| Standard| NaN| NaN|
| Percent| 12 Hour Format| Standard| ON| ON|
到目前为止,我看到的方法如下:
import xml.etree.ElementTree as ET
root = ET.parse(filename)
result = ''
for elem in root.findall('.//child/grandchild'):
# How to make decisions based on attributes even in 2.6:
if elem.attrib.get('name') == 'foo':
result = elem.text
这些方法明确提到了elem.attrib.get('name')
由于我的/System
标记中的元素不一致,我无法在我的情况下使用它。 所以我要问的是,是否有一种方法可以使用 xpath(或其他任何东西),我可以指定/System
并获取所有元素及其值?
你的 xml 仍然没有很好地形成,但假设它是固定的并且看起来像以前的版本,以下应该工作:
#fixed xml
<?xml version="1.0" encoding="UTF-8" ?>
<Settings>
<System>
<Format>Percent</Format>
<Time>12 Hour Format</Time>
<Set>Standard</Set>
</System>
<System>
<Format>Percent</Format>
<Time>12 Hour Format</Time>
<Set>Standard</Set>
<Alarm>ON</Alarm>
<Haptic>ON</Haptic>
</System>
</Settings>
现在对于代码本身:
import pandas as pd
rows, tags = [], []
#get all unique element names
for elem in root.findall('System//*'):
if elem.tag not in tags:
tags.append(elem.tag)
#now collect the required info:
for elem in root.findall('System'):
rows.append([elem.find(tag).text if elem.find(tag) is not None else None for tag in tags ])
pd.DataFrame(rows,columns=tags)
输出:
Format Time Set Alarm Haptic
0 Percent 12 Hour Format Standard None None
1 Percent 12 Hour Format Standard ON ON
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.