【发布时间】:2021-05-16 04:46:34
【问题描述】:
我正在尝试使用 Python etree 库从 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}]}
我不详细了解我可以使用该库的哪些功能,也许有更有效的方法可以实现这一点,我忽略了它......
关于如何解决这个问题的任何想法都会很棒。非常感谢!
【问题讨论】:
标签: python json xml elementtree xml.etree