Como atualizar os valores e atributos existentes do elemento xm
Introduza XML como country.xml: -
<configroot version="8.0">
<set>
<name>US</name>
<stringval>New York</stringval>
</set>
<set>
<name>UK</name>
<integerval>12</integerval>
</set>
</configroot>
stou analisando xml e levando-o para uma lista e tenho um dicionário com base no qual estou comparando e adicionando elementos xm
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")
Saída que estou obtendo é a condição de entrada original, pois está na saída para uma condição específica. A produção esperada está abaixo: -
<configroot version="8.0">
<set>
<name>US</name>
<stringval>Chicago</stringval>
</set>
<set>
<name>UK</name>
<stringval>London</stringval>
</set>
</configroot>