Mihir Patel Mihir Patel - 1 month ago 6x
Python Question

Python ElementTree won't update new file after parsing


to parse attribute's value in an XML and writing a new XML file. It will console the new updated value and write a new file. But won't update any changes in the new file. Please help me understand what I am doing wrong. Here is XML & Python code:


<?xml version="1.0"?>
<req action="get" msg="1" rank="1" rnklst="1" runuf="0" status="1" subtype="list" type="60" univ="IL" version="fhf.12.000.00" lang="ENU" chunklimit="1000" Times="1">
<f i="bond(long) hff" aggregationtype="WeightedAverage" end="2016-02-29" freq="m" sid="fgg" start="2016-02-29"/>
<f i="bond(short) ggg" aggregationtype="WeightedAverage" end="2016-02-29" freq="m" sid="fhf" start="2016-02-29"/>
<r i="hello" CalculationType="3" Calculate="1" />


import xml.etree.ElementTree as ET

with open('test.xml', 'rt') as f:
tree = ET.parse(f)

for node in tree.iter('r'):
port_id = node.attrib.get('i')
new_port_id = port_id.replace(port_id, "new")
print node



When you get the attribute i, and assign it to port_id, you just have a regular Python string. Calling replace on it is just the Python string .replace() method.

You want to use the .set() method of the etree node:

for node in tree.iter('r'):
    node.set('i', "new")
    print node