in reply to replace node in xml

This should do:

my $old_parent = $root; my $new_parent; my %modules; for my $node ($old_parent->childNodes()) { next if $node->nodeName() ne 'module'; my $mod_name = $node->getAttribute('name'); if ($mod_name eq 'all') { $new_parent = $node; } else { $old_parent->removeChild($node); $modules{$name} = $node; } } my %refcount; for my $node ($new_parent->childNodes()) { next if $node->nodeName() ne 'moduleref'; my $mod_name = $node->getAttribute('name'); my $referred_node = $modules{$name} or next; $referred_node = $referred_node->cloneNode(1) if $refcount{$mod_name}++; $new_parent->replaceChild($referred_node, $node); }

A bit or error checking is needed. You didn't specify what you wanted to do with the modules that aren't referenced. The above removes them.

Replies are listed 'Best First'.
Re^2: replace node in xml
by joeperl (Acolyte) on Dec 27, 2009 at 08:19 UTC

    hi ikegami,
    it worked, thanks a lot!!!
    but i had to change the function nodeName() to getNodeName() & childNodes() to getChildNodes()...
    probably some issue with perl versions i guess..
    in the actual file, there will be references for all the moduleref in "all", so no issues abt it..
    Thanks again...

      I was using XML::LibXML