DOM text

Fredrik Lundh fredrik at pythonware.com
Fri Aug 26 07:59:09 EDT 2005


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)

</F> 






More information about the Python-list mailing list