Martin Aspeli | 6 Feb 12:46
Picon

Copying children including text nodes

Hi,

I have two trees that were parsed with the HTML parser. The source tree is:

<html>
<head>
<body>
     Foo
     <p>Bar</p>
     Baz
</body>
</html>

The target is:

<html>
<head>
<body>
     <div id="target">Placeholder</div>
</body>
</html>

Now, I want to replace the whole of <div id="target"> tag (so, the tag 
and its children) with the *contents* of the <body> tag in the source 
tree. I obviously don't want the body tag itself.

Performance is important. Also, I don't care about the source tree after 
I'm done, so if "moving" rather than copying makes things faster/easier, 
that's OK.

What's the best way to do this? My naive approach was to do this:

sourceBody = source.find('body')
for sourceBodyChild in sourceBody:
	targetPlaceholder.addnext(sourceBodyChild)
targetPlaceholder.getparent().remove(targetPlaceholder)

However, this loses the text ("Foo"). I guess this is one case where 
dealing with text nodes explicitly would actually be better. :)

Martin

--

-- 
Author of `Professional Plone Development`, a book for developers who
want to work with Plone. See http://martinaspeli.net/plone-book

Gmane