我已输入XML作为country.xml:-
<root>
<set>
<name>US</name>
<stringval>New York</stringval>
</set>
<set>
<name>UK</name>
<integerval>12</integerval>
</set>
</root>
我正在解析xml并将其放入列表中,并且我有一个字典,基于该字典我可以比较和添加xml元素。
diction: dict = {'US':'Chicago', 'UK':'London'}
source = etree.getroot()
for key,value in diction.items()
countrylist = source.xpath('./set/name[text()=\'{}\']/..'.format(key))
if len(countrylist) == 0:
# creating new string and element
# appending element to original tree
elif len(countrylist) == 1: ###This is problematic case what to expect here to update key,value from dictionary only and replace the tag already present in xml
key = countrylist[0]
e = ElementMarker()
stringval = e.stringval
integerval = e.integerval
for element in source.findall('./set'):
name = element.find('name')
integervalue = element.find('integerval')
stringvalue = element.find('stringval')
if stringvalue is None:
source.clear()
for val in diction[name.text]:
source.append(stringval(val))
else:
continue
# writebacktoxml(source,"country.xml")
我得到的输出是原始输入条件,因为它在特定条件下处于输出状态。 预期输出如下:-
<root>
<set>
<name>US</name>
<stringval>Chicago</stringval>
</set>
<set>
<name>UK</name>
<stringval>London</stringval>
</set>
</root>
答案 0 :(得分:2)
也许您可以复制XML文件然后进行修改,而且,我认为最好一次迭代XML并与字典进行比较,而不是每次都重复字典并读取XML文件(这可能会导致性能问题) ),下面是一个示例:
import xml.etree.ElementTree as ET
xml_file = 'c:/temp/input.xml'
xml_file_output = 'c:/temp/output.xml'
values = {'US': 'Chicago', 'UK': 'London'}
with open(xml_file, 'r') as fin:
data = fin.read().splitlines(True)
with open(xml_file_output, 'w') as fout:
fout.writelines(data)
tree = ET.parse(xml_file_output)
xml_root = tree.getroot()
for set in xml_root.iter("set"):
country = set.find('name').text
if country in values:
value = values[set.find('name').text]
integerval = set.find('integerval')
if integerval is not None:
set.remove(integerval)
stringval = set.find('stringval')
if stringval is not None:
set.remove(stringval)
stringval = ET.Element('stringval')
stringval.text = value
set.append(stringval)
tree.write(xml_file_output)
这是输出:
<configroot version="8.0">
<set>
<name>US</name>
<stringval>Chicago</stringval>
</set>
<set>
<name>UK</name>
<stringval>London</stringval>
</set>
</configroot>
请注意,如果在词典中找不到国家/地区名称,则不会修改“设置”条目。