python - 使用 python 的 lxml 剥离内联标签

标签 python xml tags lxml

我必须处理 xml 文档中的两种内联标签。第一种类型的标签包含我想保留在中间的文本。我可以用 lxml 处理这个问题

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

第二种类型的标签包含我不想保留的文本。我怎样才能摆脱这些标签和他们的文字?如果可能的话,我宁愿不使用正则表达式。

谢谢

最佳答案

我认为 strip_tagsstrip_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>

关于python - 使用 python 的 lxml 剥离内联标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6476548/

相关文章:

php - MYSQL解析为XML代码

xml - 在 Axis2 中使用 XML 1.1

c++ - XML 编辑/替换的好选择

html - 最常被误用的 html 标签有哪些?

python - 请求.FILES 为空

python - 从列表 os 文件路径构建树 (Python) - 性能依赖

python - 如何在 python 库中使用非欧洲语言

python - Python3 中的字典帮助

tags - "gssd"或 "gsst"等 MP4 元数据标签是什么意思?

php - 如何设置此 PHP 打印的 HTML 表单以保留在 <p> 标记内?