* content nodes, and then iterate over the nodes.
             */
            xmlNodePtr  root;
+           xmlNodePtr  oldroot;
            xmlNodePtr  newline;
 
            root = xmlNewNode(NULL, (const xmlChar *) "content-root");
                xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
                            "could not allocate xml node");
 
-           /* This attaches root to doc, so we need not free it separately. */
-           xmlDocSetRootElement(doc, root);
+           /*
+            * This attaches root to doc, so we need not free it separately...
+            * but instead, we have to free the old root if there was one.
+            */
+           oldroot = xmlDocSetRootElement(doc, root);
+           if (oldroot != NULL)
+               xmlFreeNode(oldroot);
+
            xmlAddChildList(root, content_nodes);
 
            /*
        else
        {
            xmlNodePtr  root;
+           xmlNodePtr  oldroot PG_USED_FOR_ASSERTS_ONLY;
 
            /* set up document with empty root node to be the context node */
            doc = xmlNewDoc(version);
            if (root == NULL || xmlerrcxt->err_occurred)
                xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
                            "could not allocate xml node");
-           /* This attaches root to doc, so we need not free it separately. */
-           xmlDocSetRootElement(doc, root);
+
+           /*
+            * This attaches root to doc, so we need not free it separately;
+            * and there can't yet be any old root to free.
+            */
+           oldroot = xmlDocSetRootElement(doc, root);
+           Assert(oldroot == NULL);
 
            /* allow empty content */
            if (*(utf8string + count))