Parse an XML file to get a full tag by using Python's lxml package
<p>I've got the following XML file:</p>

<pre><code>&lt;root&gt;

    &lt;scene name="scene1"&gt;
        &lt;view ath="0" atv="10"/&gt;
        &lt;image url="img1.jgp"/&gt;
        &lt;hotspot name="hot1"/&gt;
    &lt;/scene&gt;

    &lt;scene name="scene2"&gt;
        &lt;view ath="20" atv="10"/&gt;
        &lt;image url="img2.jgp"/&gt;
        &lt;hotspot name="hot2"/&gt;
    &lt;/scene&gt;

&lt;/root&gt;
</code></pre>

<p>I'm writing a Python script using lxml package, to get the entire <code>view</code> tag within <code>scene1</code>. That is:</p>

<pre><code>&lt;view ath="0" atv="10" /&gt;
</code></pre>

<p>I've read the lxml documentation but all I can find is how to get the tag, its attributes or its content, but not the entire tag.</p>

<p>Can anybody at least point me in the right direction? Does lxml has a function or a method to achieve this?</p>

<p>Thanks,</p>

<p>Rafael </p>

<p>The XML content is a string like this:</p>

<pre><code>content = u"""\
&lt;root&gt;

    &lt;scene name="scene1"&gt;
        &lt;view ath="0" atv="10"/&gt;
        &lt;image url="img1.jgp"/&gt;
        &lt;hotspot name="hot1"/&gt;
    &lt;/scene&gt;

    &lt;scene name="scene2"&gt;
        &lt;view ath="20" atv="10"/&gt;
        &lt;image url="img2.jgp"/&gt;
        &lt;hotspot name="hot2"/&gt;
    &lt;/scene&gt;

&lt;/root&gt;
"""
</code></pre>

<p>You can parse a file; But, here, I parse a StringIO:</p>

<pre><code>tree = etree.parse(io.StringIO(content))
</code></pre>

<p>Everything is loaded in an <code>ElementTree</code>.</p>

<p>To find the views, I use a XPath expression:</p>

<pre><code>views = tree.xpath("//scene/view")
</code></pre>

<p>The result is always a list:</p>

<pre><code>for view in views:
    print(etree.tostring(view, with_tail=False))
</code></pre>

<p>You'll get:</p>

<pre><code>&lt;view ath="0" atv="10"/&gt;
&lt;view ath="20" atv="10"/&gt;
</code></pre>

python xml lxml