2011-06-25 17 views
4

xml文書では2種類のインラインタグを扱わなければならない。最初のタイプのタグは、その間に置いておきたいテキストを囲みます。私はlxmlのでこれを扱うことができますPythonのlxmlでインラインタグを取り除く

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

タグの2番目のタイプは、私が保持したくないテキストが含まれています。これらのタグとそのテキストを削除するにはどうすればよいですか?可能であれば、正規表現を使用しないことをお勧めします。私はstrip_tagsstrip_elementsはあなたがそれぞれの場合に何をしたいと思います

おかげ

答えて

10

。たとえば、このスクリプト:

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

はどうもありがとう、それは私が望んでいたまさにです。 – Panos

+0

@Mark Longair: 'strip_tags()'を使ってすべての子タグを取り除く(子にあるテキストを親にマージする)方法はありますか? – Aufwind

関連する問題