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

I have a chunk of xml code with a bunch of elements in it. I need to replace some of the data in the xml with some other values. I can make XML::Simple do this, but it mangles the order. I am now trying to get XML::LibXML to work, but I am having a great deal of trouble.

The part of the xml I am wanting to change looks like this:

<remote name="korg">

I need to be able to change the 'korg' value to something else without totally making a hash out of the document.

What I have tried looks like:

my $parser = XML::LibXML->new(); my $doc = $parser->parse_file($filename); my $root = $doc->getDocumentElement; print $doc->toString; my $query1 = '//remote[@name="korg"]/'; my ($node1) = $doc->findnodes($query1); $node1->setData('other');

This was pulled from a XML::LibXML sample. unfortunatly the sample errors out saying it cannot find the function setData in XML::LibXML::Element.

Any ideas how to make this work? I am not a total Perl newbie, but I am a total XPath newbie.

Thanks!

Replies are listed 'Best First'.
Re: How do I get LibXML to replace attribute values?
by ikegami (Patriarch) on Apr 20, 2011 at 22:55 UTC

    Get the element, and set its attribute:

    my ($node) = $doc->findnodes('//remote[@name="korg"]'); $node->setAttribute(name => 'other');

    Or get the attribute, and change its value:

    my ($node) = $doc->findnodes('//remote/@name[.="korg"]'); $node->setValue('other');

    Three key concepts:

    • Everything in the tree is a node, including attributes.
    • The square brackets are like a WHERE clause in SQL. The filter which nodes to return.
    • "." refers to the topic node. In square brackets, that's the node being tested by the square brackets.
Re: How do I get LibXML to replace attribute values?
by Anonymous Monk on Apr 20, 2011 at 22:49 UTC
    Your xpath query should be '//remote[@name="korg"]'. And use setAttribute() to change the value of the attribute;
    my $query = '//remote[@name="korg"]'; $doc->findnodes($query)->shift()->setAttribute('name', 'other');
Re: How do I get LibXML to replace attribute values?
by choroba (Cardinal) on Apr 21, 2011 at 13:23 UTC