实际上,minidom并不比其他dom解析器更难使用,如果您 不喜欢它,则可能要考虑向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()