【发布时间】:2021-12-31 19:57:04
【问题描述】:
给定下面的示例 xml:
<_Document>
<_Data1> 'foo'
<_SubData1> 'bar1' </_SubData1>
<_SubData2> 'bar2' </_SubData2>
<_SubData3> 'bar3' </_SubData3>
</_Data1>
</_Document>
我想捕获每个 SubData 值并使用字典中的 Data1 值对其进行更新,然后将该值附加到列表中。这样输出看起来像:
[{Data1: 'foo', SubData1: 'bar1'}, {Data1: 'foo', SubData2: 'bar2'}, {Data1: 'foo', SubData3: 'bar3'}]
我的代码是:
from lxml import etree
import re
new_records = []
for child in root.iter('_Document'): #finding all children with each 'Document' string
for top_data in child.iter(): #iterating through the entirety of each 'Document' sections tags and text.
if "Data" in top_data.tag:
for data in top_data:
rec = {}
if data.text is not None and data.text.isspace() is False: #avoiding NoneTypes and empty data.
g = data.tag.strip("_") #cleaning up the tag
rec[g] = data.text.replace("\n", " ") #cleaning up the value
for b in re.finditer(r'^_SubData', data.tag): #searching through each 'SubData' contained in a given tag.
for subdata in data:
subdict = {}
if subdata.text is not None: #again preventing NoneTypes
z = subdata.tag.strip("_") #tag cleaning
subdict[z] = subdata.text.replace("\n", " ") #text cleaning
rec.update(subdict) #update the data record dictionary with the subdata
new_records.append(rec) #appending to the list
不幸的是,这会输出:
[{Data1: 'foo', SubData3: 'bar3'}]
因为它只更新和追加字典的最终更新。
我尝试了不同的变体,包括在第二个 for 循环中的第一个“if”语句之后初始化一个列表,以便在每个循环通过后追加,但这需要在最后进行相当多的清理才能通过嵌套它会导致。 我还尝试在循环之外初始化空字典以更新以保留以前的更新并以这种方式追加。
我很好奇我是否遗漏了 lxml 的某些功能,或者是否有更 Python 的方法来获得所需的输出。
【问题讨论】:
标签: python python-3.x xml dictionary lxml