在Python中为XML文档中的节点设置值
-
05-07-2019 - |
题
我有一个XML文档“abc.xml”:
我需要编写一个函数replace(name,newvalue),它可以用新值替换带有'name'标签的值节点,然后将其写回磁盘。这在python中可能吗?我该怎么做?
解决方案
import xml.dom.minidom
filename='abc.xml'
doc = xml.dom.minidom.parse(filename)
print doc.toxml()
c = doc.getElementsByTagName("c")
print c[0].toxml()
c[0].childNodes[0].nodeValue = 'zip'
print doc.toxml()
def replace(tagname, newvalue):
'''doc is global, first occurrence of tagname gets it!'''
doc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue = newvalue
replace('c', 'zit')
print doc.toxml()
# cat abc.xml
<root>
<a>
<c>zap</c>
</a>
<b>
</b>
</root>
其他提示
当然有可能。 xml.etree.ElementTree模块将帮助您解析XML,查找标记和替换值。
如果您对要更改的XML文件有更多了解,那么您可以使该任务比您需要编写将处理任何XML文件的通用函数更容易。
如果您已经熟悉DOM解析,那么可以使用xml.dom包而不是ElementTree包。
不隶属于 StackOverflow