Python Minidom:改变Node的价值

Pet*_*r-W 3 python xml 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>
Run Code Online (Sandbox Code Playgroud)

我需要做的是取"描述"中的值并将其放入"链接"中,这样​​两者都说"这是一些信息!".我试过这样做:

#!/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()
Run Code Online (Sandbox Code Playgroud)

但是"n.childNodes [1] = n.childNodes [3]"似乎将两个节点链接在一起,所以当我执行"n.childNodes [1] .tagName ="link""来更正名称时两个子节点变为"链接"之前它们都是"描述".

此外,如果我使用"n.childNodes [1] .nodeValue",则更改不起作用,并且XML以其原始形式打印.我究竟做错了什么?

jco*_*ado 5

我不确定你是否可以修改DOM xml.dom.minidom(从头开始创建整个文档,新值应该可以工作).

无论如何,如果您接受基于的解决方案xml.etree.ElementTree(我强烈建议使用它,因为它提供了更友好的界面),那么您可以使用以下代码:

from xml.etree.ElementTree import ElementTree, dump

tree = ElementTree()
tree.parse('file.xml')

items = tree.findall('item')
for item in items:
    link, description = list(item)
    link.text = description.text

dump(tree)
Run Code Online (Sandbox Code Playgroud)