1

我需要能够解析一个大的 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() 时,它不会更新文件。有人可以请指出我的方式的错误。谢谢!

4

1 回答 1

0

etree.tostring(elem)返回树的字符串表示形式,因此它在您的代码中不执行任何操作。使用elem.write(xmlFile, encoding='utf-8').

于 2012-04-20T23:56:35.253 回答