On Tue, Jun 22, 2010 at 00:52, Chaitanya Yanamadala
<dr.virus.in...@gmail.com> wrote:
> i have done it this way,
> but i need some other way using a module,
snip
>> > i have an xml like this
>> > <a value="5" note=2 >
>> > <b><c>hello</c></b>
>> > </a>
>> >
>> > now i need to add a new attribute to node a.
snip

Personally, I like [XML::Twig][1].  It is a stream parser, so every
time you call flush or purge it dumps all of the document out of
memory.  This lets you process huge files.  Adding a new attribute is
easy with XML::Twig.  Just write a handler for the a tag, call the
set_att method on the element that is passed to the handler, and then
flush the record.  This will print the new document on STDOUT.

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $count = 1;
my $twig = XML::Twig->new(
        twig_handlers => {
                a => sub {
                        my ($twig, $element) = @_;
                        $element->set_att(note => $count++);
                        $element->flush;
                }
        }
);

#you should probably use parsefile instead
#but this makes the example self-contained
$twig->parse(do { local $/; <DATA> });

__DATA__
<root>
        <a value="5">
                <b><c>hello</c></b>
        </a>
        <a value="5">
                <b><c>world</c></b>
        </a>
        <a value="5">
                <b><c>how are you?</c></b>
        </a>
</root>

[1] : http://search.cpan.org/dist/XML-Twig/Twig_pm.slow


-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
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