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

标签 python xml

昨天我问如何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/

相关文章:

python - 使用json,python保存其键为元组的字典

python - 如何使用 Python 将多部分 PDF 请求发送到 OneNote

java - 处理 xml 文件时的 UTF8 编码无效

c - 使用 xmllib2 for C 获取元素值

java - XML 属性名称中的符号 '#' 会产生 DOMException

python - 修复 pyright 中的 'Import [module] could not be resolved'

python - 查找具有特定格式的数字

python - 套接字错误 : [Errno 111] Connection refused

java - 如何在 Java 中解析格式错误的 XML?

java - 使用 jaxb 处理带有可选内部标签和值的 xml