Note that there are some explanatory texts on larger screens.

plurals
  1. POIn lxml, how do I remove a tag but retain all contents?
    text
    copied!<p>The problem is this: I have an XML fragment like so:</p> <pre><code>&lt;fragment&gt;text1 &lt;a&gt;inner1 &lt;/a&gt;text2 &lt;b&gt;inner2&lt;/b&gt; &lt;c&gt;t&lt;/c&gt;ext3&lt;/fragment&gt; </code></pre> <p>For the result, I want to remove all <code>&lt;a&gt;</code>- and <code>&lt;c&gt;</code>-Tags, but retain their (text)-contents, and childnodes just as they are. Also, the <code>&lt;b&gt;</code>-Element should be left untouched. The result should then look thus</p> <pre><code>&lt;fragment&gt;text1 inner&lt;d&gt;1&lt;/d&gt; text2 &lt;b&gt;inner2&lt;/b&gt; text3&lt;/fragment&gt; </code></pre> <p>For the time being, I'll revert to a very dirty trick: I'll etree.tostring the fragment, remove the offending tags via regex, and replace the original fragment with the etree.fromstring result of this (not the real code, but should go something like this):</p> <pre><code>from lxml import etree fragment = etree.fromstring("&lt;fragment&gt;text1 &lt;a&gt;inner1 &lt;/a&gt;text2 &lt;b&gt;inner2&lt;/b&gt; &lt;c&gt;t&lt;/c&gt;ext3&lt;/fragment&gt;") fstring = etree.tostring(fragment) fstring = fstring.replace("&lt;a&gt;","") fstring = fstring.replace("&lt;/a&gt;","") fstring = fstring.replace("&lt;c&gt;","") fstring = fstring.replace("&lt;/c&gt;","") fragment = etree.fromstring(fstring) </code></pre> <p>I know that I can probably use xslt to achieve this, and I know that lxml can make use of xslt, but there has to be a more lxml native approach? </p> <p>For reference: I've tried getting there with lxml's element.replace, but since I want to insert text where there was an element node before, I don't think I can do that.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload