昨天我问如何replace text on a node with children使用迷你。
今天我也在尝试替换 <node/>
与 <node>text</node>
不幸的是,我觉得我的结果很糟糕:
import xml.dom.minidom
from xml.dom.minidom import Node
def makenode(text):
n = xml.dom.minidom.parseString(text)
return n.childNodes[0]
def setText(node, newText):
if node.firstChild==None:
str = node.toxml();
n = len(str)
str = str[0:n-2]+'>'+newText+'</'+node.nodeName+'>' #DISGUSTINGHACK!
node.parentNode.replaceChild( makenode(str),node )
return
if node.firstChild.nodeType != node.TEXT_NODE:
raise Exception("setText: node "+node.toxml()+" does not contain text")
node.firstChild.replaceWholeText(newText)
def test():
olddoc = '<test><test2/></test>'
doc=xml.dom.minidom.parseString(olddoc)
node = doc.firstChild.firstChild # <test2/>
print "before:",olddoc
setText(node,"textinsidetest2")
newdoc = doc.firstChild.toxml()
print "after: ", newdoc
# desired result:
# newdoc='<test><test2>textinsidetest2</test2></test>'
test()
虽然上面的代码有效,但我觉得这是一个巨大的 hack。我一直在仔细阅读 xml.minidom 文档,但我不确定如何做上述情况,尤其是
没有标记为 #DISGUSTINGHACK!
的黑客攻击以上。
最佳答案
您需要使用 Document.createTextNode()
创建一个文本节点,然后使用 Node.appendChild()
将其添加到所需的父节点或类似的方法:
def setText(doc, node, newText):
textnode = doc.createTextNode(newText)
node.appendChild(textnode)
为了便于使用,我在这里添加了一个 doc
参数,调用它:
setText(doc, node, "textinsidetest2")
您的makenode
函数可以完全删除。通过这些修改,您的 test()
函数打印:
before: <test><test2/></test>
after: <test><test2>textinsidetest2</test2></test>
关于python - 如何在 python 的 xml.minidom 中没有任何子节点的 xml 节点上设置文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13613592/