in reply to How can I replace a line (tag) in an XML file?
Note: I used XML::Tidy to indent your original XML code.use warnings; use strict; use XML::Twig; my $str = <<EOF; <students> <student> <name>John</name> <id>001</id> <gpa>A</gpa> </student> <student> <name>John</name> <id>002</id> <gpa>C</gpa> </student> </students> EOF my $t = XML::Twig->new( twig_handlers => { student => \&student, }, pretty_print => 'indented', ); $t->parse($str); $t->print($str); print "\n"; sub student { my ($t, $elt) = @_; if ($elt->field('id') eq '002') { $elt->first_child('gpa')->set_text('B'); } } __END__ <students> <student> <name>John</name> <id>001</id> <gpa>A</gpa> </student> <student> <name>John</name> <id>002</id> <gpa>B</gpa> </student> </students>
Update: made sub more succinct.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How can I replace a line (tag) in an XML file?
by mirod (Canon) on Sep 29, 2011 at 07:48 UTC | |
|
Re^2: How can I replace a line (tag) in an XML file?
by perlPractioner (Novice) on Sep 30, 2011 at 01:53 UTC | |
by mirod (Canon) on Sep 30, 2011 at 04:24 UTC |