Python ElementTree won't update new file after parsing
<p>Using <code>ElementTree</code> to parse attribute's value in an <strong>XML</strong> and writing a new <strong>XML</strong> 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 <strong>XML</strong> &amp; <strong>Python</strong> code:</p>

<p><strong>XML</strong></p>

<pre><code>&lt;?xml version="1.0"?&gt;
&lt;!--
--&gt;
    &lt;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"&gt;
        &lt;flds&gt;
            &lt;f i="bond(long) hff"  aggregationtype="WeightedAverage" end="2016-02-29" freq="m" sid="fgg" start="2016-02-29"/&gt;
            &lt;f i="bond(short) ggg"  aggregationtype="WeightedAverage" end="2016-02-29" freq="m" sid="fhf" start="2016-02-29"/&gt;
        &lt;/flds&gt;
    &lt;dat&gt;
        &lt;r i="hello" CalculationType="3" Calculate="1" /&gt;
    &lt;/dat&gt;
&lt;/req&gt;
</code></pre>

<p><strong>Python</strong></p>

<pre><code>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

tree.write('./new_test.xml')
</code></pre>

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

<p>You want to use the <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.set" rel="nofollow"><code>.set()</code></a> method of the etree node:</p>

<pre><code>for node in tree.iter('r'):
    node.set('i', "new")
    print node
</code></pre>

python xml xml-parsing elementtree