I've a xml file, and I'm trying to add additional element to it. the xml has the next structure :
<root>
<OldNode/>
</root>
What I'm looking for is :
<root>
<OldNode/>
<NewNode/>
</root>
but actually I'm getting next xml :
<root>
<OldNode/>
</root>
<root>
<OldNode/>
<NewNode/>
</root>
My code looks like that :
file = open("/tmp/" + executionID +".xml", 'a')
xmlRoot = xml.parse("/tmp/" + executionID +".xml").getroot()
child = xml.Element("NewNode")
xmlRoot.append(child)
xml.ElementTree(root).write(file)
file.close()
Thanks.
The ElementTree.write() method serves this purpose. Once created, an Element object may be manipulated by directly changing its fields (such as Element.text ), adding and modifying attributes ( Element.set() method), as well as adding new children (for example with Element.append() ).
xml.etree.ElementTree Module: There are two ways to parse the file using 'ElementTree' module. The first is by using the parse() function and the second is fromstring() function.
Now to fit the text inside the child element, we have to use the item. text and set a string value with the assignment operator. Append the child item object with the root object and write the XML file using the write() method and pass a filename as string.
set(key, value): We can set the attribute key on the element using set. append(subelement): This one is used to append the child element to the root or the sub elements to the main element.
You opened the file for appending, which adds data to the end. Open the file for writing instead, using the w
mode. Better still, just use the .write()
method on the ElementTree object:
tree = xml.parse("/tmp/" + executionID +".xml")
xmlRoot = tree.getroot()
child = xml.Element("NewNode")
xmlRoot.append(child)
tree.write("/tmp/" + executionID +".xml")
Using the .write()
method has the added advantage that you can set the encoding, force the XML prolog to be written if you need it, etc.
If you must use an open file to prettify the XML, use the 'w'
mode, 'a'
opens a file for appending, leading to the behaviour you observed:
with open("/tmp/" + executionID +".xml", 'w') as output:
output.write(prettify(tree))
where prettify
is something along the lines of:
from xml.etree import ElementTree
from xml.dom import minidom
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
e.g. the minidom prettifying trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With