1

I have an XML file that contains several lines like this:

<Teste  Time="380643" TT="380592" Win="-2" Xl="28" Yl="55" />
<Teste  Time="380660" TT="380592" Win="-2" Xl="28" Yl="55" />

I need to add a fixed number to every instance of the Time attribute, e.g. 380643 + 10000, and get an XML file with the new lines, e.g. <Time="390643" TT="380592" Win="-2" Xl="28" Yl="55"/>. Is this possible using Perl? If so, how? If not, what should I do?

1
  • You are right. Actually It would be something like this: <Teste Time="380643" TT="380592" Win="-2" Xl="28" Yl="55" />. Anyway alex-shesterov's answer has helped me. Commented Mar 17, 2013 at 14:03

2 Answers 2

1

Use XML::Twig with twig_roots:

my $twig=XML::Twig->new(   
  twig_roots => 
    { Time => sub { $_->set_att( TT => $_->att('TT')+10000 )->flush; } 
    },
  twig_print_outside_roots => 1 
);
$twig->parsefile('myXmlFile.xml');
Sign up to request clarification or add additional context in comments.

3 Comments

by using twig_roots => { Time => sub { $_->set_att( TT => $_->att('TT')+10000 )->flush; }, twig_print_outside_roots => 1, you don't need the final print and you will use much less memory (instead of the whole XMl file to be loaded in memory you only load the Time elements, and they're flushed after being used).
Yes, that is exactly what I needed. Just a further question: how can I write the script to add a number to TT and Win at the same time?
Time => sub { $_->set_att( TT => $_->att('TT')+10000, Win => $_->att('Win')+10000 )->flush; } XML::Twig is indeed very powerful, read the docs on Cpan if you want to learn about its possibilities. Or just remember "XML::Twig" for XML processing in Perl, in case if you need it in future )
0

You can do something like this :

#!/usr/bin/perl

# use module
use XML::Simple;

# create object
$xml = new XML::Simple;

# read XML file
$data = $xml->XMLin("data.xml");

# access XML data
$time = $data->{Time}->TT;
//do your stuff here

More : Here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.