Add new element to xml file in python and preserve indentation



I have two files which look like the following:


parent.xml



<?xml version="1.0" ?>
<persons>
<person name="Tom" surname="Tomerson"/>
<person name="Dave" surname="Davidson"/>
</persons>


child.xml



<?xml version="1.0" ?>
<person name="Mike" surname="Michaelson"/>


I want to add the element in the child file to the parent file so that i end up with a parent.xml file that looks like the following:



<?xml version="1.0" ?>
<persons>
<person name="Tom" surname="Tomerson"/>
<person name="Dave" surname="Davidson"/>
<person name="Mike" surname="Michaelson"/>
</persons>


However what i actually end up with is a parent.xml file that looks like :



<?xml version="1.0" ?>
<persons>
<person name="Tom" surname="Tomerson"/>
<person name="Dave" surname="Davidson"/>
<person name="Mike" surname="Michaelson"/></persons>


i.e the indentation of the new element does not match the previous elements. And there is no new line inserted after the new element is appended. The code i am trying is the following:



import xml.dom.minidom

class add_xml_fragment:

def add_fragment(self, file, parentFile):
childDoc = xml.dom.minidom.parse(file)
elem = childDoc.documentElement
parent_doc = xml.dom.minidom.parse(parentFile)
parent_root = parent_doc.documentElement
parent_root.appendChild(elem)
parent_doc.writexml(open(parentFile,'w'))

instance = add_xml_fragment()
instance.add_fragment("child.xml", "parent.xml")


How should i modify the above code to achieve the desired file with correct indentation and newline?


No comments:

Post a Comment