Python modify xml file

I have this xml model.

link text

So I need to add some node (see text comment) to this file. How can i do this?

I typed this partial code, but it doesn't work:

xmldoc=minidom.parse(directory)
child = xmldoc.createElement("map")
for node in xmldoc.getElementsByTagName("Environment"):
    node.appendChild(child)

      

Thanks in advance.

+2


a source to share


1 answer


I have uploaded your sample XML file and your code is working fine. Your problem is most likely related to the line: xmldoc=minidom.parse(directory)

if it is not the file path you are trying to parse not into a directory? The function parse()

parses an XML file, which it does not , automatically parses all XML files in a given directory.

If you change your code to something like below, this should work fine:



xmldoc=minidom.parse("directory/model_template.xml")
child = xmldoc.createElement("map")
    for node in xmldoc.getElementsByTagName("Environment"):
        node.appendChild(child)

      

If you then execute the: operator print xmldoc.toxml()

, you will see that the element is map

indeed added to the Environment

: element <Environment><map/></Environment>

.

+1


a source







All Articles