XML::LibXML replace element value

前端 未结 2 1718
眼角桃花
眼角桃花 2020-12-06 12:57

I want to replace a \"VAL1\" value of an element in xml file

For some reason it does not work for me:

   
TEST         


        
相关标签:
2条回答
  • 2020-12-06 13:15

    Where did you get setValue from? No XML::LibXML object has such a method.

    Furthermore, an element doesn't have a value, so you definitely cannot set it.

    "VAL1" is the value of the the element's child node, a text node.

    my ($application_id_text) = $root->findnodes('/testing/application_id/text()');
    $application_id_text->setData('VAL2');
    

    Unfortunately, that's not completely safe. What if the element has multiple text child nodes? What if it doesn't have any at all?

    The safer way is to grab the element, delete all of its children that are text nodes (which can easily done by removing all of its child nodes), and add a new text node with the desired value.

    my ($application_id_node) = $root->findnodes('/testing/application_id');
    $application_id_node->removeChildNodes();
    $application_id_node->appendText('VAL2');
    
    0 讨论(0)
  • 2020-12-06 13:17

    There is no setValue method in Node or Element classes, see the docs for list of available methods. You can remove children of the element and append new text node like this:

    $elem->removeChildNodes();
    $elem->appendText('VAL2');
    
    0 讨论(0)
提交回复
热议问题