I have a XML (example) file: test.xml
<root>
<tag1>AAA</tag1>
<tag2>BBB</tag2>
<tag3>
<tag4>DDD</tag4>
</tag3>
</root>
The result I want to achieve is, set two variables (from input): i.e.:
my $xpath = '/root/tag3/tag4'; # or '/root/tag2/tag5' or '/root/tag6'
my $xvalue = 'CCC'; # or 'EEE'
The script would check the $xpath variable, if it exists in the XML file, then it changes the text of it. If it doesn't exist in the XML file, then it creates the element with $xpath and $xvalue.
I use below script to set the text for $xpath, but how to modify it so that it would do proper things based on the $xpath existence? Thanks a lot,
open( my $output, '>', "$ofile") or die "cannot create $ofile: $!";
XML::Twig->new( twig_roots => { "$xpath" =>
sub { my $text= $_->text();
$_->set_text($xvalue);
$_->flush;
},
},
twig_print_outside_roots => $output,
pretty_print => 'indented',
)
->parsefile( "test.xml" );