libxml读取xml文件的其他方法

来源:互联网 发布:单片机卡尔曼滤波 编辑:程序博客网 时间:2024/04/27 14:12
  在前面一篇文章我提到了一种分析文档的方法,即调用xmlParseFile函数。当我看了libxml官网上的code examples之后,我发现libxml还提供了更加精准的分析方式。

1 调用xmlReadFile函数

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

[cpp] view plaincopyprint?
  1. xmlDocPtr doc = NULL;  
  2. doc = xmlReadFile(docname, NULL, XML_PARSE_DTDVALID);  

2 使用xmlParseCtxtPtr解析文件

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

[cpp] view plaincopyprint?
  1. xmlParserCtxtPtr ctxt = NULL;  
  2. xmlDocPtr doc = NULL;  
  3.   
  4. ctxt = xmlNewParserCtxt();  
  5. doc = xmlCtxtReadFile(ctxt, docnamen,NULL, 0);  

不要忘了最后释放ctxt。

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

[cpp] view plaincopyprint?
  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);  

原创粉丝点击