【发布时间】:2014-07-08 13:15:33
【问题描述】:
我在 C 中使用 libxml2 获取空节点时遇到问题。问题是节点就像
<node /> 并且 lib 在 xPath 中识别它,但是如果我尝试在其中放置更多节点,则 lib 不会这样做。
这里是我用来解析文档的代码:
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;
}
这里是添加节点的代码(如果节点类似于<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.:我无法控制节点的生成,就像那个答案所暗示的那样。
那么,如何使用 libxml2 将节点添加到空节点?
编辑:
稍微调试一下我的功能,我发现在我得到孩子的那一行:
xDivChildNode = xDivNode->xmlChildrenNode;
如果节点是<node />,那么chindremNode就会为null,那么如何保证不返回null呢?
谢谢。
【问题讨论】: