libxml读取xml文件的其他方法

      在前面一篇文章我提到了一种分析文档的方法,即调用xmlParseFile函数。当我看了libxml官网上的code examples之后,我发现libxml还提供了更加精准的分析方式。

1 调用xmlReadFile函数

xmlReadFile函数接收三个参数,第一个参数是文件名,第二个参数是编码类型,第三个参数是分析时的选项。由于提供了更多的参数,所以这个函数能更精确的处理文件。这个函数返回一个xmlDocPtr,得到这个指针后我们可以对各个节点进行操作了。

  1. xmlDocPtr doc = NULL;  
  2. doc = xmlReadFile(docname, NULL, XML_PARSE_DTDVALID);  

2 使用xmlParseCtxtPtr解析文件

libxml提供了这样一个结构体xmlParserCtxt,这个结构体可以深入控制解析的工程,先看看他是如何工作的。

  1. xmlParserCtxtPtr ctxt = NULL;  
  2. xmlDocPtr doc = NULL;  
  3.   
  4. ctxt = xmlNewParserCtxt();  
  5. doc = xmlCtxtReadFile(ctxt, docnamen,NULL, 0);  

不要忘了最后释放ctxt。

使用ctxt的一个操作就是分块处理文件,即读进文件的一部分,边读边分析。

  1. xmlParserCtxtPtr ctxt  = NULL;  
  2. xmlDocPtr doc = NULL;  
  3. static char chunk[1024];  
  4. int num = 0;  
  5. FILE* fd = NULL;  
  6.   
  7. fd = fopen(docname, "rb");  
  8. if(NULL == fd) {  
  9.     fprintf(stderr, "open error!\n");  
  10.     exit(1);  
  11. }  
  12.   
  13. num = fread(chunk, 1, 1024, fd);  
  14.   
  15. if(num <= 0) {  
  16.     fprintf(stderr, "read error!\n");  
  17.     fclose(fd);  
  18.     exit(2);  
  19. }  
  20.   
  21. ctxt = xmlCreatePushParserCtxt(NULL, NULL, chunk, num, docname);  
  22.   
  23. if(NULL == ctxt) {  
  24.     fprintf(stderr, "cannot create ctxt\n");  
  25.     fclose(fd);  
  26.     exit(3);  
  27. }  
  28.   
  29. while((num = fread(chunk,1,1024,fd)) >0) {  
  30.     xmlParseChunk(ctxt, chunk, num, 0);  
  31. }  
  32. xmlParseChunk(ctxt, chunk,0,1);  
  33.   
  34. doc = ctxt->myDoc;  
  35. num = ctxt->wellFormed;  
  36.   
  37. xmlFreeParserCtxt(ctxt);  
  38.   
  39. if(0 == num) {  
  40.     fprintf(stderr, "fail to parse!\n");  
  41.     fclose(fd);  
  42.     exit(4);  
  43. }  
  44. // handle doc  
  45.   
  46. xmlFreeDoc(doc);  
  47. fclose(fd);  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值