使用python获取xml值和标记

ttcibm8c  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(342)

我有一个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 并获取系统中的标记和值,以便我可以使用以下输出填充 Dataframe :

| 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 获取所有元素及其值?

wljmcqd8

wljmcqd81#

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

相关问题