ITSAMB has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks,
I am using a XML file in my application. I need to search the nodes and update it through perl. I am looking for a perl module, which will help me in searching and replacing the node values/attribute values efficiently. I do not have much idea about Xquery or any perl module supporting that. I was wondering if you could suggest any module which will help me here?
Thanks, Amit

Replies are listed 'Best First'.
Re: Perl module- XML Search & Replace
by Your Mother (Archbishop) on Feb 12, 2009 at 06:29 UTC

    Twig is nice, as GrandFather says. XML::LibXML is quite nice too.

    use strict; use warnings; use XML::LibXML; my $parser = XML::LibXML->new(); # Uncomment next line to try it on a file. # my $doc = $parser->parse_file( shift || die "Gimme an XML file!\n" ) +; my $doc = $parser->parse_fh(\*DATA); # This is just for demo. my @target = $doc->findnodes("//something"); my $whee = "a"; $_->setAttribute("else", $whee++) for @target; print $doc->serialize(1), $/; # For this demo. # $doc->toFile("./fixed.xml"); # For file writing. __DATA__ <?xml version="1.0"?> <root> <something/> <something/> <something/> </root> __END__ <?xml version="1.0"?> <root> <something else="a"/> <something else="b"/> <something else="c"/> </root>
Re: Perl module- XML Search & Replace
by GrandFather (Saint) on Feb 12, 2009 at 04:50 UTC

    There is only one - XML::Twig1.

    1Well, there may be others, but that's generally reckoned to be the most comprehensive general purpose XML manipulating module for Perl.


    True laziness is hard work
Re: Perl module- XML Search & Replace
by samtregar (Abbot) on Feb 12, 2009 at 05:56 UTC
    I've never used it for updating, but XML::LibXML's XPath support is very handy for finding nodes quickly.

    Another option would be to use XML::SAX to construct a pipeline reading at one end, modifying as needed in the middle and writing out the new file at the end. That would be an excellent choice if your files could be too large to load into memory all at once.

    -sam

Re: Perl module- XML Search & Replace
by Jenda (Abbot) on Feb 14, 2009 at 14:46 UTC

    It depends a lot on the complexity of the searches and the size of the XMLs. If the searches are complex and the parsed XML fits into memory then XML::LibXML might be best. If it doesn't fit in memory you'll need to use something else. XML::LibXML::SAX, XML::Twig, XML::Rules ...

    It's better to have a look at several and find the one that fits the task and your brain.