1

I was trying to edit an existing XML file based on the node attribute name value.

For example:

<books>
    <book name = 'Pride and Prejudice'   value='not available' price='10'/>
    <book name = 'To kill a Mockingbird'  value='available' price='8'/>
    <book name = 'The Face of a Stranger' value='not available' price='16'/>
</books>

The goal is if name attribute value matches then change the value attribute. For example, if the name "Pride and Prejudice" matches the search then change the value attribute to “available”.

The output should look like:

<books>
    <book name = 'Pride and Prejudice' value='available' price='10'/>
    <book name = 'To kill a Mockingbird' value='available' price='8'/>
    <book name = 'The Face of a Stranger' value='not available' price='16'/>
</books>

I was able to read the XML file and match the name values but couldn’t figure out how to change the attribute value.

Here is my code:

my $xml_data = XML::LibXML->load_xml(location => a.xml);

for my $nodes ( $xml_data->findnodes('/Books/Book') ) {

    my $att_name = $nodes->findvalue('@name');
    my $att_val  = $nodes->findvalue('@value');

    if ( $searchString eq $att_name ) {
         <how do I change the attribute value?>
    }
}

1 Answer 1

2

This should do as you want. Note that I'm unable to test anything at present

Your XPath expression /Books/Book may need fixing, as the XML data you show has elements <books> and <book>, and I have no way of knowing which is correct

for my $book ( $xml_data->findnodes('/Books/Book') ) {

    next unless $book->getAttribute('name') eq $searchString;

    $book->setAttribute('value', 'available');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.