How to create a subset of document using lxml?
<p>Suppose you have an lmxl.etree element with the contents like:</p>

<pre><code>&lt;root&gt;
    &lt;element1&gt;
        &lt;subelement1&gt;blabla&lt;/subelement1&gt;
    &lt;/element1&gt;
    &lt;element2&gt;
        &lt;subelement2&gt;blibli&lt;/sublement2&gt;
    &lt;/element2&gt;
&lt;/root&gt;
</code></pre>

<p>I can use find or xpath methods to get something an element rendering something like:</p>

<pre><code>&lt;element1&gt;
    &lt;subelement1&gt;blabla&lt;/subelement1&gt;
&lt;/element1&gt;
</code></pre>

<p>Is there a way <em>simple</em> to get:</p>

<pre><code>&lt;root&gt;
    &lt;element1&gt;
        &lt;subelement1&gt;blabla&lt;/subelement1&gt;
    &lt;/element1&gt;
&lt;/root&gt;
</code></pre>

<p>i.e The element of interest plus all it's ancestors up to the document root?</p>

<p>I am not sure there is something built-in for it, but here is a terrible, "don't ever use it in real life" type of a workaround using the <a href="http://lxml.de/api/lxml.etree._Element-class.html#iterancestors" rel="nofollow"><code>iterancestors()</code> parent iterator</a>:</p>

<pre><code>from lxml import etree as ET

data = """&lt;root&gt;
    &lt;element1&gt;
        &lt;subelement1&gt;blabla&lt;/subelement1&gt;
    &lt;/element1&gt;
    &lt;element2&gt;
        &lt;subelement2&gt;blibli&lt;/subelement2&gt;
    &lt;/element2&gt;
&lt;/root&gt;"""


root = ET.fromstring(data)
element = root.find(".//subelement1")

result = ET.tostring(element)
for node in element.iterancestors():
    result = "&lt;{name}&gt;{text}&lt;/{name}&gt;".format(name=node.tag, text=result)

print(ET.tostring(ET.fromstring(result), pretty_print=True))
</code></pre>

<p>Prints:</p>

<pre><code>&lt;root&gt;
  &lt;element1&gt;
    &lt;subelement1&gt;blabla&lt;/subelement1&gt;
  &lt;/element1&gt;
&lt;/root&gt;
</code></pre>

python python-2.7 lxml