I need to add a few lines in an XML file at a particular node, in Perl. So, I need to search for a particular node and then add those lines. Which parser would you recommend for this?
+4
A:
I recommend XML::Twig. It can modify all elements of a certain name, or just one element. It has excellent documentation, including a tutorial... and the module author is always on-call :)
This is a simple example which will append some text to all elements named "article":
use strict;
use warnings;
use XML::Twig;
my $xmlStr = <<XML;
<foo>
<article>ME ME ME</article>
<article>HE HE</article>
<particle>ME TOO</particle>
</foo>
XML
my $twig= XML::Twig->new(
twig_handlers => { article => \&article }
);
$twig->parse($xmlStr);
$twig->print();
print "\n";
exit;
sub article {
my ($twig, $art) = @_;
my $stuff = $art->text(); # get the text of article
$stuff .= ' YOU YOU YOU';
$art->set_text($stuff);
}
toolic
2010-01-28 19:12:28
I understand your handler is just an example, but in case you didn't know: you could also use $art->suffix( ' YOU YOU YOU'); Oh, and XML::Twig->new(...) is preferred over the deprecated new XML::Twig. But I like to nitpick :--)
mirod
2010-01-28 20:57:02
I'm glad you like to nitpick! I was unaware of both of these points. I'll fix the constructor call, but leave the suffix out... just so the OP sees that TIMTOWTDI. Thanks.
toolic
2010-01-28 21:04:54
@toolic: TIMTOWTD?? OP??
fixxxer
2010-01-28 22:49:03
OP (Original Poster/Post) is common vernacular in online forums. TIMTOWTDI (There's more than one way to do it) is the Perl motto. Both can be googled.
toolic
2010-01-29 00:19:12