#!/usr/bin/perl -w
# $Id: bench_libxml_complex,v 1.3 2003/09/19 18:52:26 mrodrigu Exp $
use strict;
use simple_benchmark; # to get memory size
use XML::LibXML;

use Getopt::Long;

my( $in_file, $print);
GetOptions( 'print!' => \$print, 'in_file=s' =>\$in_file); 
$in_file ||= 'test.xml';
$print= 1 unless( defined $print);

my %action=( delete     => \&elt_delete,
             prefix     => \&elt_prefix,
				     duplicate  => \&elt_duplicate,
						 change_tag => \&elt_change_tag,
					 	 erase      => \&elt_erase,
						 add_att    => \&elt_add_att,
           );
																				             

my $doc= XML::LibXML->new()->parse_file( $in_file);

foreach my $elt ($doc->findnodes( '//process[@action]'))
  { my $process= $elt->getAttribute( 'action');
		$action{$process}->( $doc, $elt)
	}

print $doc->toString if( $print);

sub elt_delete
  { my( $doc, $elt)= @_;
		$elt->parentNode->removeChild( $elt);
	}

sub elt_prefix
  { my( $doc, $elt)= @_;
    my $prefix= $doc->createElement( 'prefix');
		$prefix->appendTextNode( 'prefixed ');
		if( my $child= $elt->getFirstChild)
		  { $elt->insertBefore( $prefix, $elt->getFirstChild); }
		else
		  { $elt->appendChild( $prefix); }

  }

sub elt_duplicate
  { my( $doc, $elt)= @_;
    my $duplicate= $elt->cloneNode( 1);
		my $parent= $elt->parentNode;
		$parent->insertAfter( $duplicate, $elt);
  }

sub elt_change_tag
  { my( $doc, $elt)= @_;
		$elt->setNodeName( 'new_tag');
  }

sub elt_erase
  { my( $doc, $elt)= @_;
    my @children= $elt->childNodes;
		my $parent= $elt->parentNode;
		foreach my $child (@children)
		  { $child->unbindNode;
				$parent->insertBefore( $child, $elt);
			}
		$elt->unbindNode;
}

sub elt_add_att
  { my( $doc, $elt)= @_;
    $elt->setAttribute( new_att => "foo");
	}
