使用XPath分析XML

来源:互联网 发布:淘宝的虚拟试衣间 编辑:程序博客网 时间:2024/05/22 06:36

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>

int getXmlConfig(char *conf_file, char *obj_file_name, int name_size)
{
 int xmlret = 1;
 xmlKeepBlanksDefault(0);
 xmlDocPtr pDoc;
    
 pDoc = xmlParseFile(conf_file);
 if (pDoc == NULL)
 {
  printf("Error : no configure file!/n");
  return -1;
 }
 xmlXPathContextPtr xpathctx;
 xpathctx = xmlXPathNewContext(pDoc);
 if (xpathctx == NULL)
 {
  printf("Error : fail to create xpath context!/n");
  return -1;
 } 
  
 xmlXPathObjectPtr xpathobj;
 xpathobj = xmlXPathEvalExpression(BAD_CAST "/test/objname", xpathctx);
 if (xpathobj == NULL) {
  xmlret = -1;  
 }
 else {
  if (xpathobj->nodesetval == NULL)
   xmlret = -1;
  else {
   int number = xpathobj->nodesetval->nodeNr;
   if(number<=0)
    return -1;
   xmlNodePtr node = xpathobj->nodesetval->nodeTab[0];
   xmlChar *nameValue = xmlNodeGetContent(node);
   snprintf(obj_file_name, name_size, "%s", nameValue);
   xmlFree(nameValue);
  }
 }
 xmlXPathFreeObject(xpathobj);
 xmlXPathFreeContext(xpathctx); 
 xmlFreeDoc(pDoc);
   
 if (xmlret < 0)
  printf("Error in config file format!/n");

 return xmlret;
}
 分析的文件是:

<test>

         <objname>./test.txt</objname>

</test>

在这先记着,以后我再细细的解释。