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>The following code removes elements that don't have any <code>subelement1</code> descendants and are not named <code>subelement1</code>.</p>

<pre><code>from lxml import etree

tree = etree.parse("input.xml")  # First XML document in question

for elem in tree.iter():
    if elem.xpath("not(.//subelement1)") and not(elem.tag == "subelement1"):
        if elem.getparent() is not None:
            elem.getparent().remove(elem)

print etree.tostring(tree) 
</code></pre>

<p>Output:</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