Python minidom/xml : How to set node text with minidom api

前端 未结 1 1099
一个人的身影
一个人的身影 2021-01-03 00:53

I am currently trying to load an xml file and modify the text inside a pair of xml tags, like this:

   sometext

相关标签:
1条回答
  • 2021-01-03 01:13

    actually minidom is no more difficult to use than other dom parsers, if you dont like it you may want to consider complaining to the w3c

    from xml.dom.minidom import parseString
    
    XML = """
    <nodeA>
        <nodeB>Text hello</nodeB>
        <nodeC><noText></noText></nodeC>
    </nodeA>
    """
    
    
    def replaceText(node, newText):
        if node.firstChild.nodeType != node.TEXT_NODE:
            raise Exception("node does not contain text")
    
        node.firstChild.replaceWholeText(newText)
    
    def main():
        doc = parseString(XML)
    
        node = doc.getElementsByTagName('nodeB')[0]
        replaceText(node, "Hello World")
    
        print doc.toxml()
    
        try:
            node = doc.getElementsByTagName('nodeC')[0]
            replaceText(node, "Hello World")
        except:
            print "error"
    
    
    if __name__ == '__main__':
        main()
    
    0 讨论(0)
提交回复
热议问题