From: <ramesh.marimu...@wipro.com>
> 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>
> 
> i.e., if <name> contains a value RG0001_Down111, then the value of
> <administrative_state> should be changed as "Disabled". There are many
> occurrences like this in the same file and again the output should be
> read to another file.

#!perl
use strict;
use XML::Rules;

my $parser = XML::Rules->new(
        style => 'filter',
        rules => {
                _default => 'raw extended',
                direct_virtual_host => sub {
                        if ($_[1]->{':name'}{_content} eq 'RG0001_Down111') {
                                $_[1]->{':administrative_state'}{_content} = 
'Disabled'
                        }
                        return $_[0] => $_[1];
                }
        }
);

$parser->filter(\*DATA, \*STDOUT);

__DATA__
<root>
<hosts>
            <direct_virtual_host>
               <name>RG0001_Down111</name>
               <description/>
               <administrative_state>Enabled</administrative_state>
            </direct_virtual_host>
     <direct_virtual_host>
               <name>RG0001_Down159</name>
               <description/>
               <administrative_state>Enabled</administrative_state>
            </direct_virtual_host>
</hosts>
</root>

---------------------------------------------

The good thing is that the file may well be huge, the script will not 
store more than the data of a single <direct_virtual_host> in the 
memory at any time.

You may also look at XML::Twig.

Jenda



===== je...@krynicky.cz === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
        -- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to