satzbu has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, i want to change an xml file tags using XML::Simple for that i convert an xml file to hash and replace the tags via another hash and convert the hash as xml file this is my code using this code i cant get the output file please help me to debug the error

#!/usr/bin/perl use warnings; use strict; use Data::Dumper; use XML::Simple; my %xhash=(); my $file= $ARGV[0]; my $simple = XML::Simple->new(); my $xhash = $simple->XMLin($file); print Dumper ($xhash); my %c_hash=('a' => { 'addval' => { 'b' => { 'addval' => { 'e' => { 'addv +al' => {}, 'repv +al' => '5' }, 'c' => { 'addv +al' => {}, 'repv +al' => '3' } }, 'repval' => '2' }, 'd' => { 'addval' => {}, 'repval' => '4' } }, 'repval' => '1' }); my %repl; # lookup table: a => 1, etc. traverse(\%c_hash, sub { my ($key, $val) = @_; $repl{$key} = $val; }, "collect" ); #print Dumper \%repl; # debug traverse(\%xhash, sub { my ($key, $val, $href) = @_; if (exists $repl{$key}) { my $newkey = $repl{$key}; $href->{$newkey} = $val; delete $href->{$key}; } }, "replace" ); print Dumper \%xhash; $simple->XMLout($xhash, KeepRoot => 1, OutputFile => 'pets.fixed.xml', XMLDecl => "<?xml version='1.0'?>", ); sub traverse { my ($hash, $callback, $mode) = @_; return unless ref($hash) eq "HASH"; for my $key (keys %$hash) { my $val = $hash->{$key}; if (ref($val) eq "HASH") { traverse($val, $callback, $mode); if ($mode eq "collect") { if (exists $val->{repval}) { $callback->($key, $val->{repval}); } } } if ($mode eq "replace") { $callback->($key, $val, $hash); } } }

Replies are listed 'Best First'.
Re: XML::Simple handling
by Jenda (Abbot) on Apr 19, 2010 at 14:50 UTC

    What is it you actually want to do? If you make one step back, forget about your hashes and explain the task.

    Jenda
    Enoch was right!
    Enjoy the last years of Rome.

Re: XML::Simple handling
by Anonymous Monk on Apr 19, 2010 at 07:16 UTC

      i got nothing in the output file when i give the input xml file for example

      _INPUT FILE_ <book> <a>A <b>B <c>C</c> <e>E</e> <e>V</e> </b> <d>D</d> </a> </book> _OUTPUT FILE_ <?xml version='1.0'?> <opt></opt> _EXPECTED OUTPUT_FILE <?xml version='1.0'?> <1>A <2>B <3>C</3> <5>E</5> <5>V</5> </b> <4>D</4> </1>

        Are you sure that is really what you want to do? Your output is not XML (tag names cannot start with a number).

        If you use $xhash instead of %xhash on line 56, the program will output something, even if still not the thing you want.