I am attempting to find and replace XML attributes with new values based on indexing. I can replace the attribute values if I hard code the attribute values themselves into my find/replace function, but I need to do so via indexing, specifically for the first two listed attributes with "text" values for both the <foo_1> and <foo_2> elements. Below is the XML, along with the script I am using and the new values to be added to the XML and desired output:
The XML ("foo_bar.xml")
<?xml version="1.0" encoding="UTF-8"?>
<Overlay>
<foo_1>
<bar key="value">text_1</bar>
<bar key="value">text_2</bar>
<bar key="value">text_3</bar>
</foo_1>
<foo_2>
<bar key="value">text_4</bar>
<bar key="value">text_5</bar>
<bar key="value">text_6</bar>
</foo_2>
</Overlay>
Script
import lxml.etree as ET
xml = ET.parse("C:\\Users\\mdl518\\Desktop\\bar_foo.xml")
tree=xml.getroot()
new_val_1 = float(100/202)
new_val_2 = float(200/500)
new_val_3 = float(4/44)
new_val_4 = float(4/1000)
# Find and replace first and second "bar" subelement attribute values for each "foo" parent element
for elem in tree.getiterator():
if elem.text:
elem.text=elem.text.replace(text_1,new_val_1)
if elem.text:
elem.text=elem.text.replace(text_2,new_val_2)
if elem.text:
elem.text=elem.text.replace(text_4,new_val_3)
if elem.text:
elem.text=elem.text.replace(text_5,new_val_4)
print(elem.text)
Desired result
<?xml version="1.0" encoding="UTF-8"?>
<Overlay
<foo_1>
<bar key="value">new_val_1</bar>
<bar key="value">new_val_2</bar>
<bar key="value">text</bar>
</foo_1>
<foo_2>
<bar key="value">new_val_3</bar>
<bar key="value">new_val_4</bar>
<bar key="value">text</bar>
</foo_2>
</Overlay>
Is there a convenient way to index the subelement attribute values and replace them with the desired values (i.e. "new_val_#") and write to XML? Any assistance is most appreciated!
elem.attribin code.