我需要能够解析一个大的 xml 文件,但只查找<name>
元素并替换值。因此,我正在按如下方式进行事件驱动解析,我有以下代码:
import os, re, sys
from lxml import etree
# parse the xml file
context = etree.iterparse(xmlFile, events=('end',), tag='name')
for event, elem in context:
# this is an internal method that I call to perform regex
newElementText = searchReplace(elem.text).replace(" ", "")
# assign the elem.text to the replaced value
elem.text = newElementText
# write to the xml
etree.tostring(elem, encoding='utf-8')
我的问题是将更新的元素值写入文件。当我调用 etree.tostring() 时,它不会更新文件。有人可以请指出我的方式的错误。谢谢!