2009/5/19 <[email protected]>:
> Hi All,
Hi,
> I have a scenario where I should edit an xml file. I should change an
> element's value based on another element's value.
>
> I should change
>
> <root>
> <hosts>
> <direct_virtual_host>
> <name>RG0001_Down111</name>
> <description/>
> <administrative_state>Enabled</administrative_state>
> </host>
> </root>
>
> to
>
> <root>
> <hosts>
> <direct_virtual_host>
> <name>RG0001_Down111</name>
> <description/>
> <administrative_state>Disabled</administrative_state>
> </host>
> </root>
>
There are a number of modules that can help you, XML::Simple and
XML::Twig come to mind. I tend to use XML::LibXML. My xpath isn't
brilliant but if I were doing this, I would do something like this.
#!/bin/perl
use strict;
use warnings;
use XML::LibXML;
my $parser = XML::LibXML->new();
my $doc = $parser->parse_string(<<'EOT');
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<hosts>
<direct_virtual_host>
<name>RG0001_Down111</name>
<description/>
<administrative_state>Enabled</administrative_state>
</direct_virtual_host>
<direct_virtual_host>
<name>RG0002_Down112</name>
<description/>
<administrative_state>Enabled</administrative_state>
</direct_virtual_host>
<direct_virtual_host>
<name>RG0003_Down113</name>
<description/>
<administrative_state>Enabled</administrative_state>
</direct_virtual_host>
</hosts>
</root>
EOT
my @nodes = $doc->findnodes( '///direct_virtual_host' ); # findnodes
- returns an array of elements and stores them in @nodes
for my $node (@nodes) {
if ($node->findvalue('name') =~ /Down/xms ) { # Test the
value of
the node in @nodes
my $admin = $node->find("administrative_state");
my $newnode = $doc->createElement('administrative_state');
# Create
a new element
my $text = $doc->createTextNode('Disabled');
# Create a text element
$newnode->appendChild($text);
# Add the text to the node
$node->replaceChild($newnode, $admin->[0]);
# replace existing node
}
}
my $output = 'Host.conf';
print $doc->toString($output, 1); # Print it out or use
$doc->toFile($output, 1);
Which outputs:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<hosts>
<direct_virtual_host>
<name>RG0001_Down111</name>
<description/>
<administrative_state>Disabled</administrative_state>
</direct_virtual_host>
<direct_virtual_host>
<name>RG0002_Down112</name>
<description/>
<administrative_state>Disabled</administrative_state>
</direct_virtual_host>
<direct_virtual_host>
<name>RG0003_Down113</name>
<description/>
<administrative_state>Disabled</administrative_state>
</direct_virtual_host>
</hosts>
</root>
Have a look at the documentation for LibXML here:
http://search.cpan.org/~pajas/XML-LibXML-1.69/
I hope I've understood what your after and HTH,
Dp.
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/