在Python中为XML文档中的节点设置值
我有一个XML文档叫“abc.xml”:
我需要写一个函数,名字叫replace(name, newvalue),这个函数可以把标签为'name'的值节点替换成新的值,并且把修改后的内容保存到磁盘上。请问在Python中可以做到吗?我该怎么做呢?
2 个回答
2
当然是可以的。
xml.etree.ElementTree 这个模块可以帮助你解析 XML 文件,找到标签并替换值。
如果你对想要修改的 XML 文件有一些了解,可能会让这个任务变得简单一些,而不是写一个通用的函数来处理任何 XML 文件。
如果你已经熟悉 DOM 解析的话,可以使用 xml.dom 这个包,代替 ElementTree。
2
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>