[prog] perl XML::LibXML

Almut Behrens almut-behrens at gmx.net
Tue Feb 15 06:06:16 EST 2005


On Mon, Feb 14, 2005 at 01:49:44PM +0000, Caroline Johnston wrote:
> #make new node
>   $div_node = XML::LibXML::Element->new('div');
>   $div_node->setAttribute('id',$params->{id});
> 
> #pull out the reference nodes based on id's given as args
>  my @before_node=$body->findnodes('//*[@id="'."$params->{before}".'"]')
>  	    if $params->{before};
>  my @after_node=$body->findnodes('//*[@id="'."$params->{after}".'"]')
>  	    if $params->{after};
> 
> #if we've been told where to put it, put it there
>  if (@after_node)
>  {
>      $body->insertAfter($div_node, $after_node[0]);
>  }
>  elsif (@before_node)
>  {
>      $body->insertBefore($div_node, $before_node[0]);
>  }
> #otherwise, stick it at the end of the <body>
>  else
>  {
>      $body->appendChild($div_node);
>  }
> 
> The appendChild call works fine, but the insertBefore and insertAfter
> don't. I don't get any errors, it just doesn't insert anything. As far as
> I can tell div_node, body, before_node and after_node contain what I think
> they should contain. 

The code itself looks allright to me.  Maybe your problem is caused by
the following feature of the underlying libxml: "...the reference node
has to be a direct child of the node the function is called on." (see
the pod for XML::LibXML::Node / insertBefore()).

So, depending on what your XML document structure looks like, the
above code might fail (e.g. if the ref node passed to insertBefore()
is somewhere further down the tree).  In case you actually have a
direct-child-of-$body node with the ID in question (but there are
others with the same ID), you might need to modify your XPath
expression such that findnodes() will return the correct node as its
first list element.  Just an idea...

> 
> If I change it to something like
> 
> $body->insertBefore($div_node, $body->firstChild) 
> then the new div gets inserted after the first child of body.

in this case $body->firstChild  _is_ a direct child of $body ...

Almut



More information about the Programming mailing list