Python Minidom:更改节点的值
我正在使用 Python 的 minidom 库来尝试操作一些 XML 文件。这是一个示例文件:
<document>
<item>
<link>http://www.this-is-a-url.com/</link>
<description>This is some information!</description>
</item>
<item>
<link>http://www.this-is-a-url.com/</link>
<description>This is some information!</description>
</item>
<item>
<link>http://www.this-is-a-url.com/</link>
<description>This is some information!</description>
</item>
</document>
我需要做的是获取“描述”中的值并将其放入“链接”中,这样两者都会说“这是一些信息!”。我尝试这样做:
#!/usr/bin/python
from xml.dom.minidom import parse
xmlData = parse("file.xml")
itmNode = xmlData.getElementsByTagName("item")
for n in itmNode:
n.childNodes[1] = n.childNodes[3]
n.childNodes[1].tagName = "link"
print xmlData.toxml()
但是“n.childNodes[1] = n.childNodes[3]”似乎将两个节点链接在一起,所以当我执行“n.childNodes[1].tagName =”link “”更正名称 两个子节点都变为“链接”,而之前它们都是“描述”。
此外,如果我使用“n.childNodes[1].nodeValue”,则更改不起作用,并且 XML 会以其原始形式打印。我做错了什么?
I'm using Python's minidom library to try and manipulate some XML files. Here is an example file :
<document>
<item>
<link>http://www.this-is-a-url.com/</link>
<description>This is some information!</description>
</item>
<item>
<link>http://www.this-is-a-url.com/</link>
<description>This is some information!</description>
</item>
<item>
<link>http://www.this-is-a-url.com/</link>
<description>This is some information!</description>
</item>
</document>
What I need to do, is take the value in "description" and put it into "link" so both say "This is some information!". I've tried to do it like so:
#!/usr/bin/python
from xml.dom.minidom import parse
xmlData = parse("file.xml")
itmNode = xmlData.getElementsByTagName("item")
for n in itmNode:
n.childNodes[1] = n.childNodes[3]
n.childNodes[1].tagName = "link"
print xmlData.toxml()
However "n.childNodes[1] = n.childNodes[3]" seems to link the two nodes together, so when I do "n.childNodes[1].tagName = "link"" to correct the name BOTH child nodes become "link" where before they were both "description".
Furthermore, if I use "n.childNodes[1].nodeValue" the changes don't work and the XML is printed in it's original form. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定您是否可以使用 xml.dom.minidom 修改 DOM(不过,使用新值从头开始创建整个文档应该可以)。
无论如何,如果您接受基于 xml.etree.ElementTree 的解决方案(我强烈建议使用它,因为它提供了更友好的界面),那么您可以使用以下代码:
I'm not sure you can modify the DOM in place with
xml.dom.minidom
(creating the whole document from scratch with new values should work though).Anyway, if you accept a solution based on
xml.etree.ElementTree
(I strongly recommend using it since it provides a friendlier interface), then you could use the following code: