keegita gina keegita gina - 4 months ago 23
Perl Question

Perl and XML::Smart : How to check a node's existence based on its value?

What perl function in the XML::Smart library ( or XML::LibXML ) allows to check if a node exists before adding it?

Example:

<food>
<fruit>banana</fruit>
<fruit>apple</fruit>
<fruit>orange</fruit>
</food>


I want to add the fruit "banana" only if it doesn't already exist.
Thanks.

Answer

I don't know about XML::Smart but in XML::LibXML you want 'findnodes'.

E.g.

#!/usr/bin/env perl

use strict;
use warnings;
use XML::LibXML;

my $xml = XML::LibXML -> new() -> parse_string( do { local $/; <DATA> } );

if ( my $node =  $xml -> findnodes ( '//fruit[string()="banana"]') ) {
   print $node;
}
else {
    #insert new element
    my $new = XML::LibXML::Element->new("fruit");
    $new -> addChild (XML::LibXML::Text->new("banana"));
    $xml -> documentElement -> addChild ( $new );
}


__DATA__
<food>
<fruit>banana</fruit>
<fruit>apple</fruit>
<fruit>orange</fruit>
</food>