-2

I want to change an XML attribute value using XML::Twig. I can do this by using XML::LibXML like this

       my $doc = XML::LibXML->new->parsefile();
       my $xpath = '/model/@name';
       my ($attr) = $doc->findnodes($xpath);    
       $attr->setValue('dfdsa'); 

But I have to used XML::Twig because of some constraints

input

<model name="XXXX" oid="i">
  <system oid="1" uri="/gaia" listing="NO">
    <schema desc="HTTP Sever schema" enab="YES" name="HTTP" oid="1" prio="5">
    </schema>
  </system>
</model>

output

<model name="dfdsa" oid="i">
  <system oid="1" uri="/gaia" listing="NO">
    <schema desc="HTTP Sever schema" enab="YES" name="HTTP" oid="1" prio="5">
    </schema>
  </system>
</model>

I tried this code but it's not modifying the content

my $doc = XML::Twig->new->parsefile('pattern.xml');
my $xpath = '/model';
my ($attr) = $doc->findnodes($xpath);
$attr->set_att(name => 'dfdsa');
mirod
  • 15,923
  • 3
  • 45
  • 65
user1575765
  • 60
  • 3
  • 10
  • 1
    What did you try? Setting the value of the attribute is done with `$elt->set_att( name => 'dfdsa')` – mirod Aug 13 '12 at 06:05
  • Hello Minard, I tried below but its not modifing the content :( my $doc = XML::Twig->new->parsefile('pattern.xml'); my $xpath = '/model'; my ($attr) = $doc->findnodes($xpath); $attr->set_att( name => 'dfdsa'); – user1575765 Aug 13 '12 at 06:37
  • Even i tried with below Bud didn't worked XML::Twig->new( twig_handlers => { 'model' => sub {$_->set_att( name => 'dfdsa')} } ,)->parsefile( 'pattern.xml'); – user1575765 Aug 13 '12 at 07:05
  • it should work. Please post a proper test case, with code we can run, including the data in a _DATA__ section if possible. Without it all we can do is guess. This will also avoid your XML to be invalid. I am not sure how to fix you spelling and your messing up people's name though (Bud is a beer, minard is not my name) ;--( – mirod Aug 13 '12 at 07:12
  • 1
    your code works... if at some point you output the XML::Twig object. it doesn't magically update the file on disk. You need to have a `$doc->print`, or `$doc->print_to_file(...)` at the end of the code – mirod Aug 13 '12 at 08:44
  • @mirod : Sorry sorry I was confused!!!. Thanks alot for your suggestion – user1575765 Aug 13 '12 at 11:25

1 Answers1

1

I am very disappointed that you seem to have done almost nothing to try to solve this problem yourself. Even the XML in your question was malformed and I had to fix it.

This program will do what you want

use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig->new;
$twig->parsefile('pattern.xml');

my ($model) = $twig->findnodes('/model[@name]');
$model->set_att(name => 'dfdsa');

$twig->print(pretty_print => 'indented');

output

<model name="dfdsa" oid="i">
  <system listing="NO" oid="1" uri="/gaia">
    <schema desc="HTTP Sever schema" enab="YES" name="HTTP" oid="1" prio="5"></schema>
  </system>
</model>
Borodin
  • 126,100
  • 9
  • 70
  • 144