in reply to Using XML::XPath to change values
The following does what you want, although I don't think it's particularly pretty. I think that XML::Twig (as recommended by Cristoforo), or at least XML::LibXML would be much better. Note that both XML::XPath and XML::Twig use the same underlying parser, XML::Parser, which in turn uses Expat.
use warnings; use strict; use XML::XPath; my $xml = <<'ENDXML'; <includes> <include> <priority>9990</priority> <required>true</required> <location>/efs/dist/tpcommon/itrstemplates/latest/common/templ +ates/equities.xml</location> </include> <include disabled="true"> <priority>10001</priority> <required>true</required> <location>/efs/dist/itrs/tools/latest/common/templates/global_ +authentication.xml</location> </include> </includes> ENDXML my $xp = XML::XPath->new(xml => $xml); my $nodes = $xp->find('//includes/include'); for my $include ($nodes->get_nodelist) { for my $p ($xp->findnodes('./priority', $include)) { my $priority = $p->string_value; $p->removeChild($_) for $p->getChildNodes; $p->appendChild( XML::XPath::Node::Text->new($priority+1) ); } } my ($root) = $xp->findnodes('/'); print $root->toString, "\n";
In regards to the last two lines above, I haven't yet found an easy way to print back out the XML document, maybe I'm missing something obvious. Anyway, for comparison, here's an XML::Twig solution:
use XML::Twig; open my $ofh, '>', \my $outxml or die $!; my $twig = XML::Twig->new( twig_print_outside_roots => $ofh, twig_roots => { '/includes/include/priority' => sub { my ($twig, $elt) = @_; $elt->set_text( $elt->text+1 ); $elt->flush($ofh); }, } ); $twig->parse($xml); close $ofh; print $outxml;
I've written some things a little longer than they need to be in this code for clarity, the code could be shortened quite a bit, and also the output doesn't need to go to a string, it could be sent to a file directly.
|
|---|