加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XpathForXmlFile.cpp

发布时间:2020-12-16 06:05:35 所属栏目:百科 来源:网络整理
导读:在转自http://blog.csdn.net/shanzhizi/article/details/8822166的博文中提到:XpathForXmlFile.cpp 在bing上找到源码,贴下,写得很好,分享给大家! ========================================================================= /***********************

在转自http://blog.csdn.net/shanzhizi/article/details/8822166的博文中提到:XpathForXmlFile.cpp

在bing上找到源码,贴下,写得很好,分享给大家!

=========================================================================

  1. /********************************************************************
  2. created:2007/11/15
  3. created:15:11:200716:01
  4. filename:XpathForXmlFile.cpp
  5. author:Wangxuebin
  6. depend:libxml2.lib
  7. build:nmakeTARGET_NAME=XPathForXmlFile
  8. purpose:使用XPATH查找xml文档中的节点
  9. *********************************************************************/
  10. #include<libxml/parser.h>
  11. #include<libxml/xpath.h>
  12. #include<iostream.h>
  13. xmlXPathObjectPtrget_nodeset(xmlDocPtrdoc,constxmlChar*szXpath)
  14. {
  15. xmlXPathContextPtrcontext;//XPATH上下文指针
  16. xmlXPathObjectPtrresult;//XPATH对象指针,用来存储查询结果
  17. context=xmlXPathNewContext(doc);//创建一个XPath上下文指针
  18. if(context==NULL)
  19. printf("contextisNULLn");
  20. returnNULL;
  21. }
  22. result=xmlXPathEvalExpression(szXpath,context);//查询XPath表达式,得到一个查询结果
  23. xmlXPathFreeContext(context);//释放上下文指针
  24. if(result==NULL)
  25. printf("xmlXPathEvalExpressionreturnNULLn");
  26. if(xmlXPathNodeSetIsEmpty(result->nodesetval))//检查查询结果是否为空
  27. xmlXPathFreeObject(result);
  28. printf("nodesetisemptyn");
  29. returnresult;
  30. intmain(intargc,char*argv[])
  31. xmlDocPtrdoc=NULL;//定义解析文档指针
  32. xmlNodePtrcurNode=NULL;//定义结点指针(你需要它为了在各个结点间移动)
  33. char*szDocName=NULL;
  34. if(argc<=1)
  35. printf("Usage:%sdocnamen",argv[0]);
  36. return(0);
  37. szDocName=argv[1];
  38. doc=xmlReadFile(szDocName,"GB2312",XML_PARSE_RECOVER);//解析文件
  39. if(NULL==doc)
  40. fprintf(stderr,"Documentnotparsedsuccessfully.n");
  41. return-1;
  42. xmlChar*szXpath=BAD_CAST("/root/node2[@attribute='yes']");
  43. xmlXPathObjectPtrapp_result=get_nodeset(doc,szXpath);//查询并得到结果
  44. if(NULL==app_result)
  45. printf("app_resultisNULLn");
  46. xmlChar*szValue=NULL;
  47. if(app_result)
  48. xmlNodeSetPtrnodeset=app_result->nodesetval;
  49. for(inti=0;i<nodeset->nodeNr;i++)
  50. curNode=nodeset->nodeTab[i];
  51. if(curNode!=NULL)
  52. szValue=xmlGetProp(curNode,BAD_CAST"attribute");
  53. if(szValue!=NULL)
  54. printf("attribute=%sn",szValue);
  55. xmlFree(szValue);
  56. szValue=xmlNodeGetContent(curNode);
  57. printf("content=%sn",248); line-height:14px; margin:0px!important; padding:0px 3px 0px 10px!important"> xmlXPathFreeObject(app_result);
  58. xmlFreeDoc(doc);
  59. return0;
  60. }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读