[xml] How to properly concatenate XML trees?



Hello,


I'm new to using libxml2 and I'm trying to perform the following procedure:

  1. Create a new doc tree and assign a root node
  2. Read an existing XML file into a tree (i.e. 'subtree')
  3. Move the subtree under the root node of the tree I created
  4. Save the new doc tree to an XML file
  5. Free the new doc tree (crashes here)

Everything seems to work until Step 5 when I free the document and it causes my process to crash.  The generated output XML file (step 4) looks good however.  Here's a simplified sample of my code:

void RunXml(void)
{
    xmlDocPtr    rootDoc = NULL,    subDoc = NULL;
    xmlNodePtr rootNode = NULL, subRootNode = NULL;

     /* Creates a new XML document, a new node, and sets it as a root node */
    rootDoc = xmlNewDoc(BAD_CAST "1.0"); 
    rootNode = xmlNewNode(NULL, BAD_CAST "rootElement");
    xmlDocSetRootElement(rootDoc, rootNode);

    /* Read the subtree into a new doc */
    subDoc = xmlReadFile("/tmp/subtree.xml", NULL, 0);

    /* Get the subtree root node */
    subRootNode = xmlDocGetRootElement(subDoc);

    /* Unlink the sub-root node from the sub doc */
    xmlUnlinkNode(subRootNode);

    /* Add the sub root node into the root tree */
    xmlAddChild(rootNode, subRootNode);

    /* Save the tree to a file */
    xmlSaveFormatFileEnc("/tmp/outfile.xml", rootDoc, "UTF-8", 1);

    /* Free the root doc */
    if (rootDoc != NULL) {
        xmlFreeDoc(rootDoc);  /* <--- Crashes here */
    }

}

I've also tried minor adjustments such as creating a new temporary node using xmlNewChild() under the rootNode, and then calling xmlReplaceNode() to swap out the temp node with the subRootNode without luck.  Any ideas/suggestions of what I'm doing incorrectly?

Thanks
Jordan



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]