Search code examples
xmlperlxml-libxml

Perl XML::LibXML replace text


Simple xml file cr.xml

<book_reviewers>
    <results>
        <reviewer>
            <name>Anne</name>
            <profession>Catfish wrangler</profession>
        </reviewer>
        <reviewer>
            <name>Bob</name>
            <profession>Beer taster</profession>
        </reviewer>
        <reviewer>
            <name>Charlie</name>
            <profession>Gardener</profession>
        </reviewer>
    </results>
</book_reviewers>

I want to loop through each reviewer and replace the name with a new one

I am not trying to use both these methods, but going by other posts in the form both of these should work but I keep getting errors:

Can't locate object method "setData"

Can't locate object method "removeChildNodes

Can't locate object method "appendText"

#!/usr/bin/perl -w

use strict;
use XML::LibXML;

my $critics_file = "cr.xml";
my $parser = new XML::LibXML;   


print "Couldn't retrieve review details\n" 
    unless my $book_reviews  = $parser->parse_file($reviews_file);


foreach my $critics ($critic_details->findnodes('/book_reviewers/results/reviewer')) {

    my $value = $critics->findvalue('name');    #returns the correct name
    $value->removeChildNodes();
    $value->appendText('new_name');

     ##ONLY EITHER THE ABOVE METHOD OR THE ONE BELOW - NOT BOTH

    my $node  = $critics->findnodes('.//name.text()');#returns the correct name
    $node->setData('new_name');


}

Can anyone see where I am going wrong?

Cheers


Solution

  • Trying to get you into TIMTOWTDI, here is another example with more compact code:

    You can find all the <name>…</name> elements directly, and you can iterate over them immediately, using the 'default' variable $_.

    use strict;
    use warnings;
    
    use utf8;
    
    use XML::LibXML;
    
    my $filename = "cr.xml";
    
    my $parser = XML::LibXML->new();
    my $critic_details = $parser->parse_file("$filename") or die;
    
    my $new_name = "new_name";
    
    # find ALL the <book_reviewers><results><reviewers><name> nodes
    foreach ($critic_details
      ->findnodes("book_reviewers/results/reviewer/name")
    ) {
      $_->removeChildNodes();
      $_->appendText($new_name);
    }
    
    use XML::LibXML::PrettyPrint;
    my $pretty = XML::LibXML::PrettyPrint->new(
      indent_string =>' ' x4,
      element       => {
        compact       => [qw| name profession |],
        }
      );
    $pretty->pretty_print($critic_details);
    
    print $critic_details->toString;
    
    __END__
    

    enjoy!