Python Minidom:更改Nod的值

2024-10-04 09:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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将以其原始形式打印。我做错什么了?


Tags: comhttpurlinformationiswwwlinksome
1条回答
网友
1楼 · 发布于 2024-10-04 09:23:30

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

无论如何,如果您接受基于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)

相关问题 更多 >