我如何"重置"在Python 2.7中使用LXML的etree?
我有一个包含文件列表的文件。对于此列表中的每个文件,我将信息存储在LXML的元素树中,然后将LXML写入文件。我写入文件后能够做的就是将etree恢复到初始状态。
从概念上讲,这就是我所处的位置:
from lxml import etree
for file in list:
quiz = etree.Element('quiz')
open file and process contents:
"add a bunch of stuff to etree"
etree.SubElement(quiz,'stuff')
"print etree to xml file"
dataOut = etree.tostring(quiz, pretty_print = True)
output_file.write(dataOut)
"reset etree to blank file"
答案 0 :(得分:1)
我没有看到以下设置与您拥有的设置有任何问题:
from lxml import etree
for item in ["test1", "test2", "test3"]:
quiz = etree.Element('quiz')
etree.SubElement(quiz, 'stuff', attrib={"attr": item})
print etree.tostring(quiz, pretty_print = True)
print "---"
打印:
<quiz>
<stuff attr="test1"/>
</quiz>
---
<quiz>
<stuff attr="test2"/>
</quiz>
---
<quiz>
<stuff attr="test3"/>
</quiz>
---
我没有看到测验堆栈,这可能意味着问题出现在您真实代码的其他地方。