Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Modifying XML with LibXML

by jasal (Initiate)
on Nov 28, 2013 at 10:23 UTC ( [id://1064789]=perlquestion: print w/replies, xml ) Need Help??

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

I am using LibXML and have nasty issue. My XML looks like this:
<root> <parameters> <key name="Repetitions" value="500" /> <key name="Mode" value="COLD" /> ... </parameters> </root>
I want to change "Repetitions" value in my code, then save the file. I have tried "setData" but it "Can't locate object method "setData"". What is the right method to select the correct key and then alter it?

Replies are listed 'Best First'.
Re: Modifying XML with LibXML
by choroba (Cardinal) on Nov 28, 2013 at 10:36 UTC
    For attributes, use setValue, not setData:
    #!/usr/bin/perl use warnings; use strict; use XML::LibXML; my $xml = 'XML::LibXML'->load_xml( string => << '======' ); <root> <parameters> <key name="Repetitions" value="500" /> <key name="Mode" value="COLD" /> </parameters> </root> ====== my $root = $xml->documentElement; my ($value) = $root->findnodes('parameters/key/@value[.="500"]'); $value->setValue(501); print $root->serialize;

    Or, if you find it too verbose, here is the same in XML::XSH2:

    open file.xml ; set /root/parameters/key/@value[.="500"] 501 ; save :b ;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Playing around with XML::LibXML::Attribute objects is usually unnecessary. It's easier to select the element and then use getAttribute and setAttribute, or if you have a vaguely recent copy of XML::LibXML, just treat the element as a hashref...

      use strict; use warnings; use XML::LibXML 2; my $xml = 'XML::LibXML'->load_xml(IO => \*DATA); $_->{value}++ for $xml->findnodes('//key[@name="Repetitions"]'); print $xml->toString; __DATA__ <root> <parameters> <key name="Repetitions" value="500" /> <key name="Mode" value="COLD" /> ... </parameters> </root>
      use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1064789]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-19 22:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found