目前三种最流行的开源 c/c++解析xml库:libxml、Xerces、expat ,且三者都是跨平台的。
Xerces-C++ (C++版本):
xerces2-j (java版本):
java版dom及sax方式解析示例:
expat:
一、libxml库下载
libxml官网:
libxml库下载:
libxml文档下载:
二、libxml安装
#解压安装文件
[root@localhost xmllib]# tar -xzvf libxml2-git-snapshot.tar.gz
#然后cd进入解压后的目录,运行初始配置文件,也可使用 ./configure --prefix=$HOME/libxml 指定安装目录
#不指定安装目录,则默认安装在系统目录 /usr/local/include/libxml2
[root@localhost libxml2-2.8.0]# ./configure
#make编译
[root@localhost libxml2-2.8.0]# make
#make install安装
[root@localhost libxml2-2.8.0]# make install
注:libxml无论输入/输出,默认只支持UTF-8,如果需要输出GB2312或其他编码的内容,则需要iconv工具库来转码(如libiconv
(libiconv-1.11.tar.gz),安装与上同)
三、libxml示例
libxml 支持dom和sax方式解析,下面是从文档里抽取的一个示例(更多的实现,可参考API文档及sample文档):
1、story.xml
- <?xml version="1.0"?>
- <story>
- <storyinfo>
- <author>John Fleck</author>
- <datewritten>June 2, 2002</datewritten>
- <keyword>example keyword</keyword>
- </storyinfo>
- <body>
- <headline>This is the headline</headline>
- <para>This is the body text.</para>
- </body>
- </story>
2、keyword.c
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <libxml/xmlmemory.h>
- #include <libxml/parser.h>
- void
- parseStory (xmlDocPtr doc, xmlNodePtr cur) {
- xmlChar *key;
- cur = cur->xmlChildrenNode;
- while (cur != NULL) {
- if ((!xmlStrcmp(cur->name, (const xmlChar *)"keyword"))) {
- key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
- printf("keyword: %s\n", key);
- xmlFree(key);
- }
- cur = cur->next;
- }
- return;
- }
- static void
- parseDoc(char *docname) {
- xmlDocPtr doc;
- xmlNodePtr cur;
- doc = xmlParseFile(docname);
-
- if (doc == NULL ) {
- fprintf(stderr,"Document not parsed successfully. \n");
- return;
- }
-
- cur = xmlDocGetRootElement(doc);
-
- if (cur == NULL) {
- fprintf(stderr,"empty document\n");
- xmlFreeDoc(doc);
- return;
- }
-
- if (xmlStrcmp(cur->name, (const xmlChar *) "story")) {
- fprintf(stderr,"document of the wrong type, root node != story");
- xmlFreeDoc(doc);
- return;
- }
-
- cur = cur->xmlChildrenNode;
- while (cur != NULL) {
- if ((!xmlStrcmp(cur->name, (const xmlChar *)"storyinfo"))){
- parseStory (doc, cur);
- }
-
- cur = cur->next;
- }
-
- xmlFreeDoc(doc);
- return;
- }
- int
- main(int argc, char **argv) {
- char *docname;
-
- if (argc <= 1) {
- printf("Usage: %s docname\n", argv[0]);
- return(0);
- }
- docname = argv[1];
- parseDoc (docname);
- return (1);
- }
3、编译运行
[root@localhost txlib]# gcc keyword.c -o keyword -I/usr/local/include/libxml2 -lxml2
[root@localhost txlib]#
[root@localhost txlib]# ./keyword story.xml
keyword: example keyword
阅读(5930) | 评论(0) | 转发(0) |