I have input XML as country.xml:-
<root>
<set>
<name>Countries</name>
<elements>
<name>US</name>
<city>
<val>New York</val>
<val>Las Vegas</val>
</city>
</elements>
<elements>
<name>UK</name>
<city>
<val>London</val>
</city>
</elements>
</set>
</root>
I am parsing xml and taking it into a list and i have a dictionary based on which I am comparing and adding xml elements.
diction: dict = {'US':['New York', 'Chicago'], 'UK':['OXFORD', 'London']}
source = etree.getroot()
for key,value in diction.items()
countrylist = source.xpath('./elements/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]
else:
countinue
# writebacktoxml(source,"country.xml")
Output I am getting is original input condition as it is in output for specific condition. Expected output is below:-
<root>
<set>
<name>Countries</name>
<elements>
<name>US</name>
<city>
<val>New York</val>
<val>Chicago</val>
</city>
</elements>
<elements>
<name>UK</name>
<city>
<val>OXFORD</val>
<val>London</val>
</city>
</elements>
</set>
</root>
key = countrylist[0]does not update your xml. It only creates a new reference/variable key pointing to countrylist[0]