Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use XML::LibXML to replace an XML node

Tags:

xml

perl

Can someone help me please? I need to replace an XML node using Perl with the XML::LibXML module

This is the fragment of the XML file:

<utenti>
    <utente>
        <username>amministratore</username>
        <useremail>[email protected]</useremail>
        <password>0000</password>
    </utente>
</utenti>

And I need to replace the value of the password.

In particular I have to find in the XML file the user with a particular username (given by the cookie $userCookie) and replace his password with the variable $newPSW.

I've tried this:

    my $psw = $doc->findnodes("/utenti/utente[username=\"$userCookie\"]/password");
    my $parent = $psw->parentNode;
    $parent->removeChild($psw);


    my $password = XML::LibXML::Element->new('password');
    $password->appendText( $newPSW );
    $parent->appendChild($password);

but everytime the browser give me the following error:

Can't locate object method "parentNode" via package "XML::LibXML::NodeList"

It seems to no find any method I use.

Can someone help?

like image 403
ambdere Avatar asked Dec 04 '25 16:12

ambdere


2 Answers

You get a XML::LibXML::NodeList as result. And this object has no function parentNode. You have to get the first element of the array and then call the method parentNode on it.

The first object will be an object of class XML::LibXML::Node and this has a funtion parentNode.

for more details see the documentation of XML::LibXML::Node

my $psw = $doc->findnodes("/utenti/utente[username=\"$userCookie\"]/password");
my $parent = $psw->[0]->parentNode;
$parent->removeChild($psw->[0]);
like image 109
Jens Avatar answered Dec 06 '25 08:12

Jens


XML::XSH2, a wrapper around XML::LibXML, can make your life easier:

set /utenti/utente[username="amministratore"]/password $newPSW ;
like image 27
choroba Avatar answered Dec 06 '25 06:12

choroba