在转自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;
- xmlXPathObjectPtrresult;
- context=xmlXPathNewContext(doc);
- if(context==NULL)
- printf("contextisNULLn");
- returnNULL;
- }
- result=xmlXPathEvalExpression(szXpath,context);
- xmlXPathFreeContext(context);
- if(result==NULL)
- printf("xmlXPathEvalExpressionreturnNULLn");
- if(xmlXPathNodeSetIsEmpty(result->nodesetval))
- xmlXPathFreeObject(result);
- printf("nodesetisemptyn");
- returnresult;
- intmain(intargc,char*argv[])
- xmlDocPtrdoc=NULL;
- xmlNodePtrcurNode=NULL;
- char*szDocName=NULL;
- if(argc<=1)
- printf("Usage:%sdocnamen",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_resultisNULLn");
- 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=%sn",szValue);
- xmlFree(szValue);
- szValue=xmlNodeGetContent(curNode);
- printf("content=%sn",248); line-height:14px; margin:0px!important; padding:0px 3px 0px 10px!important"> xmlXPathFreeObject(app_result);
- xmlFreeDoc(doc);
- return0;
- }
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|