首页 > 解决方案 > 使用 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(或其他任何东西)?

标签: pythonxmlxml-parsing

解决方案


您的 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

推荐阅读