11
votes

I am trying to strip XML tags from a document using Python, a language I am a novice in. Here is my first attempt using regex, whixh was really a hope-for-the-best idea.

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

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

That failed miserably. I would like to know how it should be done with regex.

Secondly, I googled and found: http://code.activestate.com/recipes/440481-strips-xmlhtml-tags-from-string/

which seems to work. But I would like to know is there a simpler way to get rid of all xml tags? Maybe using ElementTree?

3
Opening the file with option "w" will start with an empty file and your iterating over it is useless. - halex
The best way is to use a parser, such as BeautifulSoup. The second answer to this question will help. (You want to use from BeautifulSoup import BeautifulStoneSoup and use BeautifulStoneSoup in the parsing instead). - David Robinson
You can't parse [X]HTML with regex - kreativitea
To be clear- are you trying to change the document in place, or write it to a new document? - David Robinson
@David Robinson. For the above example I was trying to change it in place. I was then going to modify it to create a new document - user485498

3 Answers

4
votes

Please, note, that usually it is not normal to do it by regular expressions. See Jeremiah answer.

Try this:

import re

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

The most reliable way to do this is probably with LXML.

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

It will avoid the problems with "parsing" XML with regular expressions, and should correctly handle escaping and everything.

15
votes

An alternative to Jeremiah's answer without requiring the lxml external library:

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

Should work with any Python >= 2.5