首页 > 解决方案 > 如何在 Python 中从 XML 中的列表中提取子元素

问题描述

我正在尝试使用 Pythonetree库从 XML 列表中提取元素,并使用这些元素完成生成输出 JSON。

这个想法是通过一系列 XPATH 来提取我想要的元素。我不想遍历 XML 中的所有元素,因为它们有很多。

XML 看起来与此类似:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Line xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Data>
        <Date>2020-01-02</Date>
        <Id>id_1</Id>
        <CodDevice>567</CodDevice>
        <DataList>
            <Item>
                <Row>1</Row>
                <Value>34.67</Value>
                <Description>WHEELS</Description>
                <Tag>tag1</Tag>
            </Item>
            <Item>
                <Row>2</Row>
                <Value>38.04</Value>
                <Description>MOTOR</Description>
                <Tag>tag1</Tag>
            </Item>
        </DataList>
        <MetaList>
            <Metadata>
                <Row>1</Row>
                <Value>some value</Value>
            </Metadata>
        </MetaList>
    </Data>
</Line> 

我正在考虑的方法如下:

import xml.etree.ElementTree as ET
import json

data = """<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Line xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Data>
        <Date>2020-01-02</Date>
        <Id>id_1</Id>
        <CodDevice>567</CodDevice>
        <DataList>
            <Item>
                <Row>1</Row>
                <Value>34.67</Value>
                <Description>WHEELS</Description>
                <Tag>tag1</Tag>
            </Item>
            <Item>
                <Row>2</Row>
                <Value>38.04</Value>
                <Description>MOTOR</Description>
                <Tag>tag1</Tag>
            </Item>
        </DataList>
        <MetaList>
            <Metadata>
                <Row>1</Row>
                <Value>some value</Value>
            </Metadata>
        </MetaList>
    </Data>
</Line>     
"""

tag_list = [
'./Data/Date',
'./Data/Id',
'./Data/CodDevice',
'./Data/DataList/Item/Row',
'./Data/DataList/Item/Value',
'./Data/DataList/Item/Description',
'./Data/MetaList/Metadata/Row',
'./Data/MetaList/Metadata/Value'
]

elem_dict= {}
  
parser = ET.XMLParser(encoding="utf-8")
root = ET.fromstring(data, parser=parser)

for tag in tag_list:
    for item in root.findall(tag):
        elem_dict[item.tag] = item.text
print(json.dumps(elem_dict))

如您所见,我尝试生成一个 JSON,当我将 XPATH 传递给列表元素时,它会覆盖它们,生成以下输出:

{"Date": "2020-01-02", "Id": "id_1", "CodDevice": "567", "Row": "1", "Value": "some value", "Description": "MOTOR"}

但我想得到的是类似于:

{"Id":"id_1","CodDevice":"567","DataList":[{"Row":1,"Value":34.67,"Description":"WHEELS"}, {"Row":2,"Value":38.04,"Description":"MOTOR"}],"MetaList":[{"Row":1,"Value":some value}]}

我不详细知道我可以使用该库的哪些功能,也许有一种更有效的方法可以实现这一点,我忽略了它......

关于如何解决这个问题的任何想法都会很棒。非常感谢你!

标签: pythonjsonxmlelementtreexml.etree

解决方案


你的任务包括:

  • 过滤源 XML 树,
  • 更改元素的名称及其结构(例如,将Item元素更改为列表的元素)
  • 生成“多级”(嵌套)输出。

这就是为什么我认为最自然的方法是编写一些自定义代码。

从一个获取 XML 元素文本的函数开始(它将被进一步使用):

def getTxt(elem):
    return elem.text.strip()

然后定义另一个函数将子元素添加到字典中:

def addChildren(dct, elem, childNames, fn=getTxt):
    for it in elem:
        tag = it.tag
        if tag in childNames:
            dct[tag] = fn(it)

参数:

  • dct - 要添加内容的字典。
  • elem - 源元素。
  • childNames - 在elem中寻找并服务的孩子的名字。
  • fn - 为每个元素生成内容的函数。

要获取两个列表的内容,请定义另一个函数:

def getItems(elem):
    lst = []
    for it in elem:
        dct = {}
        addChildren(dct, it, ['Row', 'Value', 'Description'])
        lst.append(dct)
    return lst

最后一步是主要代码,假设您的 XML 树位于root中:

dct = {}
nd = root.find('Data')
addChildren(dct, nd, ['Date', 'Id', 'CodDevice'])
addChildren(dct, nd, ['DataList', 'MetaList'], getItems)

现在dct包含(经过一些重新格式化后):

{
  'Date': '2020-01-02',
  'Id': 'id_1',
  'CodDevice': '567',
  'DataList': [
    {'Row': '1', 'Value': '34.67', 'Description': 'WHEELS'},
    {'Row': '2', 'Value': '38.04', 'Description': 'MOTOR'}
  ],
  'MetaList': [
    {'Row': '1', 'Value': 'some value'}
  ]
}

如果要将其保存为 JSON 字符串,请运行json.dumpjson.dumps

我不确定输出是否应该包含Date键(您的tag_list 包含它,但预期的输出不包含)。如果不需要,请从第一个childNames中删除“日期”


推荐阅读