easy dom creation using LibXML?

Robin Berjon robin.berjon at expway.fr
Thu Jan 12 16:04:12 GMT 2006

On Jan 12, 2006, at 16:44, Richard Jolly wrote:
>   Wrap elements $tag as the successive ancestors of the element,  
> returns
> the
>   new element. $elt->wrap_in( 'td', 'tr', 'table') wraps the  
> element as
> a
>   single cell in a table for example.
> which may be going to far, but can be very nice when you find you need
> them.

I don't think it's going too far, it's clearly useful stuff and not  
terribly complicated (untested).

sub wrapIn {
   my $node = shift;
   my @parents = @_;

   my $dad = shift @parents;
   my ($ns, $ln) = ref $dad ? @$dad : (undef, $dad);
   my $elem = $node->ownerDocument->createElementNS($ns, $ln);
   return $elem unless @parents;
   return wrapIn($elem, @parents);

This accepts both namespace and namespace-less modes:

   wrapIn($node, 'td', 'tr');
   wrapIn($node, [$xhtmlNS, 'td'], [$xhtmlNS, 'tr']);

It'll work identically on elements, text nodes, cdata sections,  
comments, PIs, and document fragments.

It would be easy to add an item to the array refs that would be a  
hash of attributes to add to that specific element upon creation. One  
could also make the $node argument optionally be an array ref so that  
several nodes could be wrapped at once.

Robin Berjon
    Senior Research Scientist
    Expway, http://expway.com/

More information about the london.pm mailing list