我目前正在尝试加载一个xml文件并修改一对xml标签内的文本,如下所示:
<anode>sometext</anode>
Run Code Online (Sandbox Code Playgroud)
我目前有一个名为helper的函数getText,用于获取sometext上面的文本.现在我需要修改childnodes我想在节点内部修改具有上面显示的XML片段的节点,以更改sometext为othertext.常见的API补丁getText功能如下脚注所示.
所以我的问题是,这就是我们如何获取文本,如何编写一个名为的伴随辅助函数setText(node,'newtext').我更喜欢它是在节点级别上运行的,并且可以自己找到子节点,并且运行稳健.
之前的一个问题有一个接受的答案,上面写着" 我不确定你是否可以修改DOM ".这是真的吗?Minidom是如此破碎,它是否有效只读?
通过脚注,读取<anode>和之间的文本</anode>,我感到惊讶没有直接简单的单个minidom函数存在,并且这个小帮助函数在Python xml教程中建议:
import xml.dom.minidom
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
# I've added this bit to make usage of the above clearer
def getTextFromNode(node):
return getText(node.childNodes)
Run Code Online (Sandbox Code Playgroud)
在StackOverflow的其他地方,我从2008年看到了这个接受的答案:
node[0].firstChild.nodeValue
Run Code Online (Sandbox Code Playgroud)
如果用minidom读取它有多难,我不会惊讶地看到有人说"就是不要这样做!" 当你问如何编写可能修改XML文档的Node结构的东西时.
更新下面的答案显示它并不像我想象的那么难.
小智 6
实际上 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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13002 次 |
| 最近记录: |