DOM text

Richard Lewis richardlewis at fastmail.co.uk
Fri Aug 26 09:15:45 EDT 2005


On Fri, 26 Aug 2005 13:59:09 +0200, "Fredrik Lundh"
<fredrik at pythonware.com> said:
> Robert Kern wrote:
> 
> > You might find that the more Pythonic XML modules are better suited to
> > handling mixed content. I've been using lxml and ElementTree quite
> > successfully.
> 
> fwiw, here's an ET snippet that inserts an anchor element inside
> a paragraph element:
> 
> # from lxml.etree import * # or
> # from cElementTree import * # or
> from elementtree.ElementTree import *
> 
> p = XML("<p>a link and some <b>bold</b> text</p>")
> 
> a = Element("a", href="link")
> 
> text = p.text # "a link and some "
> 
> p.text = text[:2] # "a " is left after <p>
> a.text = text[2:6] # "link" goes inside <a>
> a.tail = text[6:] # " and some" goes after </a>
> 
> p.insert(0, a)
> 
> print tostring(p) # "<p>a <a href="link">link</a> and some <b>bold</b>
> text</p>"
> 
> (this works with ET, cET, lxml.etree, and any other ET-com-
> patible library, of course)
> 
Thanks for this suggestion.

I've not come accress ElementTree before, but it looks really useful
(plus there are Debian packages :-)

The only thing is that I've already written quite a lot of my code using
minidom and mixing the two sounds like a recipe for disaster. But I'll
certainly keep ET in mind for my next Python/XML project!

Cheers,
Richard



More information about the Python-list mailing list