Python从文档中剥离XML标记

9 python regex xml

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

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

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

那次失败了.我想知道如何使用正则表达式来完成它.

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

这似乎工作.但我想知道是否有一种更简单的方法来摆脱所有的xml标签?也许使用ElementTree?

Jer*_*iah 22

最可靠的方法是使用LXML.

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

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


gab*_*ous 12

替代Jeremiah的答案,不需要lxml外部库:

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

应该适用于任何Python> = 2.5


def*_*fuz 5

请注意,通常通过正则表达式来完成此操作是不正常的。参见耶利米的回答

尝试这个:

import re

text = re.sub('<[^<]+>', "", open("/path/to/file").read())
with open("/path/to/file", "w") as f:
    f.write(text)
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

17313 次

最近记录:

10 年,7 月 前