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.
So, how add nodes to a empty node with libxml2?
EDIT:
Debugging my function a little i find that in the line of i get the child:
xDivChildNode = xDivNode->xmlChildrenNode;
if the node is <node />
then the chindremNode will be null, so how to guarantee that not even return null?
thanks.
Based on your debug log, you need to replace
xmlNodePtr xDivChildNode = xDivNode; //->xmlChildrenNode;
if( (xAddType == eAddChildPrev) || (xAddType == eAddChildNext) )
{
if (xDivNode->xmlChildrenNode == NULL){
xmlNodeAddContent(xDivNode,BAD_CAST " ");//avoiding empty nodes, puting content in the node.
}
xDivChildNode = xDivNode->xmlChildrenNode;
}
To make sure the libxml don't add an empty node to your xml file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.