Python modify an xml file

帅比萌擦擦* 提交于 2019-12-08 01:06:11

问题


I have this xml model.

link text

So I have to add some node (see the text commented) to this file. How I can do it?

I have writed 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.


回答1:


I downloaded your sample xml file and your code works fine. Your problem is most likely with the line: xmldoc=minidom.parse(directory), should this not be the path to the file you are trying to parse not to a directory? The parse() function parses an XML file it does not automatically parse all the 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 statement: print xmldoc.toxml() you will see that the map element has indeed been added to the Environment element: <Environment><map/></Environment>.



来源:https://stackoverflow.com/questions/2836132/python-modify-an-xml-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!