удаление встроенных тегов с помощью Python's lxml - PullRequest
4 голосов
/ 25 июня 2011

Мне приходится иметь дело с двумя типами встроенных тегов в XML-документах. Первый тип тегов заключает в себе текст, который я хочу оставить между. Я могу справиться с этим с lxml

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

Второй тип тегов включает текст, который я не хочу хранить. Как я могу избавиться от этих тегов и их текста? Я бы предпочел не использовать регулярные выражения, если это возможно.

Спасибо

1 Ответ

10 голосов
/ 25 июня 2011

Я думаю, что strip_tags и strip_elements - это то, что вы хотите в каждом случае.Например, этот скрипт:

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)

... производит следующий вывод:

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