nodesappendchildxml-libxml

How to appendChild() to the BEGINNING of $node's children?


$ man XML::LibXML::Node
  appendChild
     $childnode = $node->appendChild( $childnode );

   The function will add the $childnode
   to the end of $node's children.

OK that's great. But how do I instead "add the $childnode to the BEGINNING of $node's children"?

(No blabbersome examples from me today. All I did was just change one word. The astute reader understands the original man page. So they also will understand when I just change one word.)

How to insert the same element on beginning and on the end of the list with insertBefore and appendChild? is for JavaScript, not LIBXML.


Solution

  • what about:

    use XML::LibXML;
    
    my $doc = XML::LibXML->new()->parse_string('<root><child1/><child2/></root>');
    my $root = $doc->documentElement;
    
    # Create a new child node to insert
    my $new_node = XML::LibXML::Element->new('newChild');
    
    # Check if the root has any children
    if ($root->hasChildNodes()) {
        # Insert the new node before the first child
        $root->insertBefore($new_node, $root->firstChild);
    } else {
        # If no children, just append as the only child
        $root->appendChild($new_node);
    }
    
    # Output the updated document
    print $doc->toString(1);