Search code examples
perlxml-twig

xml modification using perl


This is my sample xml file (snipped version of deployment plan for weblogic application).

<?xml version="1.0" encoding="UTF-8"?>
<deployment-plan>
  <application-name>ear-my-service</application-name>
  <variable-definition>
    <variable>
      <name>characteristics</name>
      <value>myTestEAR</value>
    </variable>
    <variable>
      <name>Url</name>
      <value>ABC</value>
    </variable>
    <variable>
      <name>time</name>
      <value>300</value>
    </variable>
  </variable-definition>
</deployment-plan>

I want to update the value when the name is characteristics. I looked around and put together this script.

#!/usr/bin/perl

use strict;
use warnings;
use XML::Twig;

my $data = shift ||die $!;

my $t= XML::Twig->new(
    twig_handlers => {
        q{project[string(name) =~ /\bcharacteristics\b/]/value} => \&value,
    },
    pretty_print => 'indented',
);
$t->parsefile( $data );
$t->print;

sub value {
    my ($twig, $value) = @_;
    $value->set_text("myTestEAR_Modified");
}

However, it doesn't change the value to myTestEAR_Modified. Am I doing it incorrectly?


Solution

  • The tag name in the XML is variable, not project, replace it in the condition (q{variable[string(name)...) and it will work.