我正在使用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>
我需要做的是,把“description”中的值放到“link”中,所以两个都说“这是一些信息!”。我试过这样做:
#!/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.child nodes[1]=n.childNodes[3]”似乎将两个节点链接在一起,所以当我执行“n.childNodes[1]时,要更正名称,两个子节点都会变成“link”,而在这之前它们都是“description”。
此外,如果我使用“n.childNodes[1].nodeValue”,则更改不起作用,XML将以其原始形式打印。我做错什么了?
我不确定您是否可以用
xml.dom.minidom
修改DOM(不过,从头开始用新值创建整个文档应该可以)。无论如何,如果您接受基于
xml.etree.ElementTree
的解决方案(我强烈建议您使用它,因为它提供了更友好的界面),那么您可以使用以下代码:相关问题 更多 >
编程相关推荐