当前位置:   article > 正文

使用libxml2对xml进行SAX读取_libxml2 sax

libxml2 sax

//下面的程序是从这里的例子修改过来的

//查找并打印出<w:sectPr>元素,属性值,和它的子元素值

//属性值必须在双引号里面,否则libxml通过SAX解析不了

 

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <string>
  5. #include <iostream>
  6. #include "libxml/SAX2.h"
  7. #include "libxml/xmlstring.h"
  8. int g_element_count = 0;
  9. static void OnStartElementNs(
  10. void *ctx,
  11. const xmlChar *localname,
  12. const xmlChar *prefix,
  13. const xmlChar *URI,
  14. int nb_namespaces,
  15. const xmlChar **namespaces,
  16. int nb_attributes,
  17. int nb_defaulted,
  18. const xmlChar **attributes)
  19. {
  20. if (!xmlStrcmp(localname, BAD_CAST"sectPr"))
  21. {
  22. ++g_element_count;
  23. std::cout<<"<<<<<<<<<<<<<<<<<<<<<<"<<std::endl<<std::endl;
  24. }
  25. if (g_element_count)
  26. {
  27. std::cout<<"element : "<< prefix<<":"<<localname << std::endl;
  28. for (int i=0; i<nb_attributes; ++i)
  29. {
  30. std::string str = (char *)attributes[5*i+3];
  31. xmlChar *attr_value = xmlCharStrdup(str.substr(0, str.find("\"")).c_str());
  32. std::cout<<"<<<< "<<attributes[5*i+1]<<":"<<attributes[5*i]<< "=" << attr_value <<std::endl;
  33. xmlFree(attr_value);
  34. }
  35. }
  36. }
  37. static void OnEndElementNs(
  38. void* ctx,
  39. const xmlChar* localname,
  40. const xmlChar* prefix,
  41. const xmlChar* URI )
  42. {
  43. if (!xmlStrcmp(localname, BAD_CAST"sectPr"))
  44. {
  45. --g_element_count;
  46. }
  47. }
  48. static void OnCharacters(void *ctx, const xmlChar *ch, int len)
  49. {
  50. if (g_element_count)
  51. {
  52. std::string str = (char *)ch;
  53. std::string value = str.substr(0, str.find('<'));
  54. std::cout<<value<<std::endl;
  55. }
  56. }
  57. int FindElement(FILE *f)
  58. {
  59. char chars[1024];
  60. int res = fread(chars, 1, 4, f);
  61. if (res <= 0)
  62. {
  63. return 1;
  64. }
  65. xmlInitParser();
  66. xmlSAXHandler SAXHander;
  67. memset(&SAXHander, 0, sizeof(xmlSAXHandler));
  68. SAXHander.initialized = XML_SAX2_MAGIC;
  69. SAXHander.startElementNs = OnStartElementNs;
  70. SAXHander.endElementNs = OnEndElementNs;
  71. SAXHander.characters = OnCharacters;
  72. xmlParserCtxtPtr ctxt = xmlCreatePushParserCtxt(
  73. &SAXHander, NULL, chars, res, NULL
  74. );
  75. while ((res = fread(chars, 1, sizeof(chars)-1, f)) > 0)
  76. {
  77. if(xmlParseChunk(ctxt, chars, res, 0))
  78. {
  79. xmlParserError(ctxt, "xmlParseChunk");
  80. return 1;
  81. }
  82. }
  83. xmlParseChunk(ctxt, chars, 0, 1);
  84. xmlFreeParserCtxt(ctxt);
  85. xmlCleanupParser();
  86. return 0;
  87. }
  88. int main(int argc, char *argv[])
  89. {
  90. FILE *fd = fopen(argv[1], "rb");
  91. FindElement(fd);
  92. fclose(fd);
  93. return 0;
  94. }


 



 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/709521
推荐阅读
相关标签
  

闽ICP备14008679号