Python修改xml文件 [英] Python modify an xml file

查看:127
本文介绍了Python修改xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个xml模型。

链接文本

因此,我必须在该文件中添加一些节点(请参见注释文本)。
我该怎么做?

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)

预先感谢。

推荐答案

我下载了示例XML文件,并且您的代码运行正常。您的问题很可能与以下行有关: xmldoc = minidom.parse(directory),这不应该是您尝试解析的文件而不是目录的路径吗? parse()函数解析一个XML文件,它自动解析给定目录中的所有XML文件。

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)

如果然后执行以下语句: print xmldoc.toxml(),您会看到 map 元素确实已添加到 Environment 元素:< Environment>< map />< / Environment>

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>.

这篇关于Python修改xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆