expat 编程入门

expat 是一款高性能的 xml 解析工具包。出自名家  James Clark 之手。firefox 就是使用了 expat 作为 html解析器。expat有优异的性能表现,比其它的解析器快 1倍到几十倍,视解析器的语言不同。expat 是使用面向数据流的解析。这不同于 dom的解析方式。面向数据流的解析的一个显著优点是: 可以在读入整个文档之前进行解析。这在处理大型文档和流式文件时(例如网页)尤其有用。 expat 针对数据流的解析做了很多细节的处理,比如,可以暂停/恢复解析。

开始学习 expat,你只需要掌握三个 api:

1 XML_Parser XML_ParserCreate(const XML_Char*encoding) 

 构造一个新的解析器。

2 XML_SetElementHandler(XML_Parser p,
                      XML_StartElementHandler start,
                      XML_EndElementHandler end);

  注册一个处理器 

3 int XML_Parse(XML_Parser p, const char *s, int len, int isFinal) 

    解析 xml 数据流

在下面的例子中,我们要捕获一段 html 代码中的 链接( <a> ) 标签。

 1 #include <expat.h>
 2 #include <stdio.h>
 3 #include <string.h>
 4 static char strhtml[] = { "<html><head></head><body><a target= \"_blank\" href=\"www.labfan.com\"> this is labfan</a></body></html>" };
 5 static  void href_begin_handler (void *userData, const XML_Char *name, const XML_Char **atts)
 6 {
 7     int index = 0;
 8     if (strcmp( name, "a" ) == 0 )
 9     {
10         printf( " I get the node a " );
11         while ( atts[index] )
12         {
13             if ( strcmp( atts[index], "href" ) == 0 )
14             {
15                 printf( "this auch link to:  %s\n", atts[index+1] );
16                 break;
17             }
18             index +=2;
19         }
20     }
21     return ;
22 }
23 int main()
24 {
25     XML_Parser parser;
26     if!( parser = XML_ParserCreate( NULL ) ) )
27     {
28         printf( "bad praser\n" );
29     };
30     XML_SetElementHandler( parser, href_begin_handler, NULL );
31     if ( XML_STATUS_ERROR ==  XML_Parse( parser, strhtml, strlen( strhtml ), 0 ) )
32     {
33         printf( "failed to parser: %s( line:%d, column:%d )\n", XML_ErrorString( XML_GetErrorCode( parser ) ),
34                                          XML_GetCurrentLineNumber( parser ), XML_GetCurrentColumnNumber( parser ));
35     return -1;
36     }
37     return 0;

38 } 

代码运行结果:

  I get the node a this auch link to:  www.labfan.com

代码解释:

 如前所述,我们使用三个函数来获得需要的结果。

 第 26 行用 XML_ParserCreate( NULL ) 创建一个解析器。 参数 NULL 表示不指派字符集( 只有 ascii字符 )。 你也可以指定其它的字符集。expat 内置支持的字符集有四种:

  • UTF-8
  • UTF-16
  • ISO-8859-1
  • US-ASCII

第 30 行 XML_SetElementHandler( parser, href_begin_handler, NULL ) 为前面创建的解析器 parser 注册 element handler。 第二个参数 href_begin_handler 是在进入结点的时候执行。第三个参数在退出 element 的时候执行。

第 31 行 XML_Parse( parser, strhtml, strlen( strhtml ), 0 ) 为 parser 指派实际要处理的字串。第二个参数 strhtml 和第三个参数分别是要处理的字串的首地址和字符串长度。 第四个参数?

相关链接:

1、using expat   是expat 官网提供的一个教程的链接。

2、 Benchmarking XML Parsers 对六款 xml parser 做了基准测试。

3、expat API 参考


范晨鹏
------------------
软件是一种态度
成功是一种习惯


原文地址:https://www.cnblogs.com/diylab/p/2042401.html