开发者

stripping inline tags with python's lxml

开发者 https://www.devze.com 2023-03-15 13:44 出处:网络
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

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


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消