Python从文档中剥离XML标记

时间:2012-10-10 15:57:24

标签: python xml regex

我正在尝试使用Python来删除文档中的XML标记,这是我新手使用的语言。这是我第一次尝试使用正则表达式,whixh真的是一个希望最好的想法。

mfile = file("somefile.xml","w")

for line in mfile:
    re.sub('<./>',"",line) #trying to match elements between < and />

悲惨地失败了。我想知道如何使用正则表达式。

其次,我用Google搜索并找到:http://code.activestate.com/recipes/440481-strips-xmlhtml-tags-from-string/

似乎有用。但我想知道有没有更简单的方法来摆脱所有的xml标签?也许使用ElementTree?

3 个答案:

答案 0 :(得分:22)

最可靠的方法是使用LXML

from lxml import etree
...
tree = etree.parse('somefile.xml')
notags = etree.tostring(tree, encoding='utf8', method='text')
print(notags)

它将避免使用正则表达式“解析”XML的问题,并且应该正确处理转义和所有内容。

答案 1 :(得分:11)

在不需要lxml外部库的情况下替代Jeremiah的答案:

import xml.etree.ElementTree as ET
...
tree = ET.fromstring(Text)
notags = ET.tostring(tree, encoding='utf8', method='text')
print(notags)

可以使用任何Python&gt; = 2.5

答案 2 :(得分:0)

  

请注意,通常用正则表达式来表达是不正常的。请参阅Jeremiah answer

试试这个:

import re

text = re.sub('<[^<]+>', "", open("/path/to/file").read())
with open("/path/to/file", "w") as f:
    f.write(text)
相关问题