如何在python中的xml.minidom中没有任何孩子的xml节点上设置文本?

War*_* P 4 python xml

昨天我问如何使用 minidom用子节点替换节点上的文本

今天我也试图<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()
Run Code Online (Sandbox Code Playgroud)

虽然上面的代码有效,但我觉得这是一个巨大的黑客。我一直在仔细阅读 xml.minidom 文档,但我不确定如何处理上述情况,尤其是在没有#DISGUSTINGHACK!上面标记的 hack 的情况下。

Mar*_*ers 5

您需要创建一个 Text 节点,使用Document.createTextNode(),然后使用Node.appendChild()或类似方法将其添加到所需的父节点:

def setText(doc, node, newText):
    textnode = doc.createTextNode(newText)
    node.appendChild(textnode)
Run Code Online (Sandbox Code Playgroud)

doc为了便于使用,我在此处添加了一个参数,将其调用为:

setText(doc, node, "textinsidetest2")
Run Code Online (Sandbox Code Playgroud)

您的makenode功能可以完全删除。通过这些修改,您的test()函数将打印:

before: <test><test2/></test>
after:  <test><test2>textinsidetest2</test2></test>
Run Code Online (Sandbox Code Playgroud)