python - 使用 Python 获取 XML 值和标签
问题描述
我有一个 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
并获取系统中的标签和值,以便我可以使用以下输出填充数据框:
| 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
标签中的元素不一致。所以我要问的是是否有一种方法可以使用我可以指定/System
并获取所有元素及其值的 xpath(或其他任何东西)?
解决方案
您的 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
推荐阅读
- java - 相当于 java PBKDF2WithHmacSHA1 的 Python
- greenkeeper - 当其他组也存在时,我可以将默认组包含到 greenkeeper.json
- java - 如何从用户输入中转义撇号
- r - R 错误中的 3D 绘图
- angular - Angular 6 - 如何向材料表添加分页
- python-3.x - 在python中从pdf文件中读取和提取文本时单词之间没有空格?
- android - LinearLayout 变色(平滑动画)
- javascript - 如何处理 AMP 的 CORS
- python - numpy 数组在 matplotlib.pyplot.imread() 之后是不可变的
- polymer - Polymer3.x 音频被缓存