Python writing to an xml file
<p>I am trying to write to an xml file.  I have changed a specific element in my code, and am able to get it to print successfully.  I need to have it written to the file, without changing the structure of the file.<br>
My code:</p>

<p>import os
from lxml import etree</p>

<pre><code>directory = '/Users/eeamesX/work/data/expert/EFTlogs/20160725/IT'
XMLParser = etree.XMLParser(remove_blank_text=True)
for f in os.listdir(directory):
    if f.endswith(".xml"):

        xmlfile = directory + '/' + f



        tree = etree.parse(xmlfile, parser=XMLParser)
        root = tree.getroot()

        hardwareRevisionNode = root.find(".//hardwareRevision")



        if hardwareRevisionNode.text == "5":
            print " "
            print "Old Tag: " + hardwareRevisionNode.text

            x = hardwareRevisionNode.text = "DVT2"

            print "New Tag " +  hardwareRevisionNode.text
</code></pre>

<p>When I try various methods of opening and closing the file, it just deletes all the data in the xml file.  Using this method </p>

<pre><code>outfile = open(xmlfile, 'w')
oufile.write(etree.tostring(tree))
outfile.close()
</code></pre>

<p>Changed the code structure of my file to be one long line.</p>

<p>If you are wanting to replace a value within an existing XML file then use:</p>

<pre><code>tree.write(xmlfile) 
</code></pre>

<p>Currently you are simply overwriting your file entirely and using the incorrect method (<code>open()</code>). <code>tree.write()</code> is normally what you would want to use. It might look something like this:</p>

<pre><code>tree = etree.parse(xmlfile, parser=XMLParser)
root = tree.getroot()
hardwareRevisionNode = root.find(".//hardwareRevision")
if hardwareRevisionNode.text == "5":
    print "Old Tag: " + hardwareRevisionNode.text
    hardwareRevisionNode.text = "DVT2"
    print "New Tag: " +  hardwareRevisionNode.text
    tree.write(xmlfile)
</code></pre>

<p>â³ <a href="https://docs.python.org/2/library/xml.etree.elementtree.html" rel="nofollow">https://docs.python.org/2/library/xml.etree.elementtree.html</a></p>

python xml lxml elementtree