Linux(Ubuntu10.04 )下libxml2的安装以及使用示例

libxml2的安装:

1.安装包下载地址:http://xmlsoft.org/,我下载的地方是http://xmlsoft.org/sources/old/

2.下载好压缩包后,对其进行解压,解压的命令是:sudo tar xvzf libxml2-2.7.1.tar.gz

3.配置,编译安装过程:

解压好之后,进入解压好的文件夹中:

cd libxml2-2.7.1

(默认路径安装)

sudo ./configure

sudo make

sudo make install

(自己设置安装路径)

或则

sudo ./configure --prefix /home/user/myxml/xmlinst

sudo make

sudo make install

export PATH=/home/user/myxml/xmlinst/bin:$PATH

 

我是按照默认路径安装的,因此下面的示例编译方法都是针对默认路径的。

libxml2经典应用示例xmlCreator.cpp:

 1 #include <stdio.h>
 2 #include <libxml/parser.h>
 3 #include <libxml/tree.h>
 4 
 5 int main(int argc,char **argv)
 6 {
 7     xmlDocPtr doc = NULL;/*document pointer*/
 8     xmlNodePtr root_node = NULL,node = NULL,node1 = NULL;/*node pointers*/
 9     //Creates a new document,a node and set it as a root node
10     doc = xmlNewDoc(BAD_CAST"1.0");
11     root_node = xmlNewNode(NULL,BAD_CAST"root");
12     xmlDocSetRootElement(doc,root_node);
13     //creates a new node,which is "attached" as child node of root_node node.
14     xmlNewChild(root_node,NULL,BAD_CAST"node1",BAD_CAST"content of node1");
15     
16     //xmlNewProp()creates attributes,which is "attached" to an node.
17     node = xmlNewChild(root_node,NULL,BAD_CAST"node3",BAD_CAST"node has attributes");
18     xmlNewProp(node,BAD_CAST"attribute",BAD_CAST"yes");
19     
20     //Here goes another way to create nodes.
21     node = xmlNewNode(NULL,BAD_CAST"node4");
22     node1 = xmlNewText(BAD_CAST"other way to create content");
23     
24     xmlAddChild(node,node1);
25     xmlAddChild(root_node,node);
26 
27     //Dumping document to stdio or file
28     xmlSaveFormatFileEnc(argc > 1 ? argv[1]:"-",doc,"UTF-8",1);
29 
30     /*free the document*/
31     xmlFreeDoc(doc);
32     xmlCleanupParser();
33     xmlMemoryDump();//debug memory for regression tests
34     
35     return 0;
36 }

编译过程:此处是cpp文件,因此是,g++ xmlCreator.cpp -o xmlCreator -I /usr/local/include/libxml2 -L /usr/local/lib -lxml2

如果是c文件,则应该改为:gcc xmlCreator.cpp -o xmlCreator -I /usr/local/include/libxml2  -L /usr/local/lib -lxml2

******-I 后接头文件目录 -L后接lib库目录

 

......$ gcc xmlCreator.cpp -o xmlCreator -I /usr/local/include/libxml2 -lxml2
/tmp/ccPeKBRE.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status

......$ g++ xmlCreator.cpp -o xmlCreator -I /usr/local/include/libxml2 -lxml2        ---------------ok

 

 因此,出现这种错误的时候,要注意看是不是编译器用错了,用gcc编译C程序,用g++编译C++程序,对号入座就没有问题了。

生成xmlCreator文件后,运行结果如下:

1 <?xml version="1.0" encoding="UTF-8"?>
2 <root>
3   <node1>content of node1</node1>
4   <node3 attribute="yes">node has attributes</node3>
5   <node4>other way to create content</node4>
6 </root>

到此,一个使用libxml2库创建xml文件的简单例子就讲完了。。。。。。

posted on 2012-04-21 08:36  COS  阅读(2055)  评论(0编辑  收藏  举报