Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stripping inline tags with python's lxml

I have to deal with two types of inline tags in xml documents. The first type of tags enclose text that I want to keep in-between. I can deal with this with lxml's

etree.tostring(element, method="text", encoding='utf-8')

The second type of tags include text that I don't want to keep. How can I get rid of these tags and their text? I would prefer not to use regular expressions, if possible.

Thanks

like image 906
Panos Avatar asked Jun 25 '11 07:06

Panos


1 Answers

I think that strip_tags and strip_elements are what you want in each case. For example, this script:

from lxml import etree

text = "<x>hello, <z>keep me</z> and <y>ignore me</y>, and here's some <y>more</y> text</x>"

tree = etree.fromstring(text)

print etree.tostring(tree, pretty_print=True)

# Remove the <z> tags, but keep their contents:
etree.strip_tags(tree, 'z')

print '-' * 72
print etree.tostring(tree, pretty_print=True)

# Remove all the <y> tags including their contents:
etree.strip_elements(tree, 'y', with_tail=False)

print '-' * 72
print etree.tostring(tree, pretty_print=True)

... produces the following output:

<x>hello, <z>keep me</z> and <y>ignore me</y>, and
here's some <y>more</y> text</x>

------------------------------------------------------------------------
<x>hello, keep me and <y>ignore me</y>, and
here's some <y>more</y> text</x>

------------------------------------------------------------------------
<x>hello, keep me and , and
here's some  text</x>
like image 188
Mark Longair Avatar answered Nov 15 '22 00:11

Mark Longair