用lxml python更改元素值

时间:2012-04-20 23:50:58

标签: python lxml

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

1 个答案:

答案 0 :(得分:0)

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