在转自http://blog.csdn.net/shanzhizi/article/details/8822166的博文中提到:XpathForXmlFile.cpp
在bing上找到源码,贴下,写得很好,分享给大家!
=========================================================================
- /********************************************************************
- created:2007/11/15
- created:15:11:200716:01
- filename:XpathForXmlFile.cpp
- author:Wangxuebin
- depend:libxml2.lib
- build:nmakeTARGET_NAME=XPathForXmlFile
- purpose:使用XPATH查找xml文档中的节点
- *********************************************************************/
- #include<libxml/parser.h>
- #include<libxml/xpath.h>
- #include<iostream.h>
- xmlXPathObjectPtrget_nodeset(xmlDocPtrdoc,constxmlChar*szXpath)
- {
- xmlXPathContextPtrcontext;//XPATH上下文指针
- xmlXPathObjectPtrresult;//XPATH对象指针,用来存储查询结果
- context=xmlXPathNewContext(doc);//创建一个XPath上下文指针
- if(context==NULL)
- printf("contextisNULL\n");
- returnNULL;
- }
- result=xmlXPathEvalExpression(szXpath,context);//查询XPath表达式,得到一个查询结果
- xmlXPathFreeContext(context);//释放上下文指针
- if(result==NULL)
- printf("xmlXPathEvalExpressionreturnNULL\n");
- if(xmlXPathNodeSetIsEmpty(result->nodesetval))//检查查询结果是否为空
- xmlXPathFreeObject(result);
- printf("nodesetisempty\n");
- returnresult;
- intmain(intargc,char*argv[])
- xmlDocPtrdoc=NULL;//定义解析文档指针
- xmlNodePtrcurNode=NULL;//定义结点指针(你需要它为了在各个结点间移动) @H_404_231@char*szDocName=NULL;
- if(argc<=1)
- printf("Usage:%sdocname\n",argv[0]);
- return(0);
- szDocName=argv[1];
- doc=xmlReadFile(szDocName,"GB2312",XML_PARSE_RECOVER);//解析文件
- if(NULL==doc)
- fprintf(stderr,"Documentnotparsedsuccessfully.\n");
- return-1;
- xmlChar*szXpath=BAD_CAST("/root/node2[@attribute='yes']");
- xmlXPathObjectPtrapp_result=get_nodeset(doc,szXpath);//查询并得到结果
- if(NULL==app_result)
- printf("app_resultisNULL\n");
- xmlChar*szValue=NULL;
- if(app_result)
- xmlNodeSetPtrnodeset=app_result->nodesetval;
- for(inti=0;i<nodeset->nodeNr;i++)
- curNode=nodeset->nodeTab[i];
- if(curNode!=NULL)
- szValue=xmlGetProp(curNode,BAD_CAST"attribute");
- if(szValue!=NULL)
- printf("attribute=%s\n",szValue);
- xmlFree(szValue);
- szValue=xmlNodeGetContent(curNode);
- printf("content=%s\n",248); line-height:14px; margin:0px!important; padding:0px 3px 0px 10px!important"> xmlXPathFreeObject(app_result);
- xmlFreeDoc(doc);
- return0;
- }