简体   繁体   English

如何使用lxml重置etree

[英]How to reset etree using lxml

How do I "reset" an etree using LXML in Python 2.7? 如何在Python 2.7中使用LXML“重置” etree?

I have one file that contains a list of files. 我有一个包含文件列表的文件。 For each of the files in this list I store the information in an element tree in LXML, then write the LXML to file. 对于此列表中的每个文件,我将信息存储在LXML的元素树中,然后将LXML写入文件。 What I'd like to be able to do once I write to file is restore the etree to its initial state. 一旦写入文件,我想做的就是将etree恢复到其初始状态。

Conceptually this is where I'm at: 从概念上讲,这就是我的位置:

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"

I don't see any issues with the following setup similar to the one you have: 我看不到以下设置与您的设置类似的任何问题:

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 "---"

which prints: 打印:

<quiz>
  <stuff attr="test1"/>
</quiz>

---
<quiz>
  <stuff attr="test2"/>
</quiz>

---
<quiz>
  <stuff attr="test3"/>
</quiz>

---

I don't see quizzes stack which probably means the problem is somewhere else in your real code. 我看不到测验堆栈,这可能意味着问题出在实际代码中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM