Question

I'm trying to change an XML attribute using Perl.

The XML file looks like this:

<Node>
  <NodeX attr1="1" attr2="2" attr3="3"/>
</Node>

the Perl script contains:

my @nodes = $doc->findnodes("//Node/Nodex");;
if (@nodes) {
  my $res = $nodes[0]->hasAttribute("attr3");
  if ($res) {
    foreach (@nodes) {
      $_->setAttribute('attr3', "10");
    }
  }
}

As result the script does not change the attribute. I have already tested the permissions and the script can write and read the XML file using print.

setAttribute seems to do nothing at all despite hasAttribute returning true.

Was it helpful?

Solution

The name of the node is NodeX, not Nodex. That is all that is wrong with your code (except that, from your comments, it seems you may not be writing the altered XML back to the file) but this shows a more concise method that you may prefer.

use strict;
use warnings;

use XML::LibXML;

my $doc = XML::LibXML->load_xml(string => <<'__END_XML__');
<Node>
  <NodeX attr1="1" attr2="2" attr3="3"/>
</Node>
__END_XML__

my ($attr) = $doc->findnodes('/Node/NodeX/@attr3');

$attr->setValue(10) if $attr;

print $doc->toString;

output

<?xml version="1.0"?>
<Node>
  <NodeX attr1="1" attr2="2" attr3="10"/>
</Node>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top