How parse XML empty node with Libxml2? In C



I have a problem getting empty nodes with libxml2 in C. The problem is the node is like <node /> and the lib recognizes it in the xPath, but if i try to put more nodes inside that him the lib don't do it.


Here the code i'm using to parse document:



xmlDocPtr xApiXmlUtilsGetDocFile(char *pcDocName)
{
xmlDocPtr xDoc;
xDoc = xmlReadFile(pcDocName,"utf-8",XML_PARSE_NOBLANKS);

if (xDoc == NULL)
{
fprintf(stderr, "Document not parsed successfully. \n");
return NULL;
}
TRACE("Document parsed successfully.");
return xDoc;
}


Here the code to add nodes (put correctly if the node is something like <node></node>):



int lApiAddElement(xmlDocPtr xDoc, char* pcXPATHBrother, char* pcChildName, char* pcChildContent, AddType_t xAddType)
{
xmlXPathObjectPtr xPathObj;

/* Create xpath evaluation context */
xPathObj = xApiXmlUtilsGetNodeSet(xDoc, BAD_CAST pcXPATHBrother);
if( xPathObj == NULL )
{
return -1;
}

// Get the div node
xmlNodeSetPtr xNodes = xPathObj->nodesetval;
xmlNodePtr xDivNode = xNodes->nodeTab[0];

xmlNodePtr xDivChildNode = xDivNode; //->xmlChildrenNode;
if( (xAddType == eAddChildPrev) || (xAddType == eAddChildNext) )
{
xDivChildNode = xDivNode->xmlChildrenNode;
}

xmlNodePtr xHeadingNode = xmlNewNode(0, BAD_CAST pcChildName);
xmlNodePtr xHeadingChildNode = xmlNewText(BAD_CAST pcChildContent);
xmlAddChild(xHeadingNode, xHeadingChildNode);

// Add the new element to the existing tree after the text content
if( (xAddType == eAddPrev) || (xAddType == eAddChildPrev) )
{
xmlAddPrevSibling(xDivChildNode, xHeadingNode);
}
else
{
if( xAddType == eAddChildNext )
{
xmlAddSibling(xDivChildNode, xHeadingNode);
}
else
{
xmlAddNextSibling(xDivChildNode, xHeadingNode);
}
}

//if you want to display the result
xmlDocDump(stdout, xDoc);

return 0;
}


OBS.: I don't have control over the generation of nodes, like that answer suggests.


How to convert <node/> to <node></node> with libxml (converting empty elements to start-end tag pairs)


So, how add nodes to a empty node with libxml2?


thanks.


No comments:

Post a Comment