Libxml2庫提供了C語言解析和構造xml文檔的接口,爲後臺C語言處理程序和前臺應用程序提供了一種通用的通迅方式。 html
本文以libxml2-2.6.30版原本說明Libxml2庫的使用方法。 node
1. 編譯庫文件 api
libxml2-2.6.30.tar.gz文件解壓後,進入libxml2-2.6.30文件夾,順序執行如下命令: spa
chmod +x ./configure 指針 ./configure code make xml make install htm |
「chmod +x ./configure」命令增長configure腳本的可執行權限; 接口
「./configure」腳本根據當前編譯系統的實際狀況生成相應的makefile文件; ci
「make」命令執行上一命令中生成的makefile文件生成相應的目標文件;
「make install」命令主要把目標文件拷貝到/usr/local目錄下,
/usr/local/lib目錄下爲如下庫文件: libxml2.a libxml2.la libxml2.so libxml2.so.2 libxml2.so.2.6.30 pkgconfig xml2Conf.sh /usr/local/include/libxml2目錄是Libxml庫使用時須要的頭文件,包含在libxml子目錄下; |
2. 使用Libxml2庫
Libxml2庫的api參考能夠從http://www.xmlsoft.org/html/index.html查詢。下面以解析一個簡單的xml文件爲例,給出一個完整的例子。
Xml文檔:
<ioMsg> <type>she</type> <subtype> <st1>123</st1> <st2>563</st2> </subtype> </ioMsg> |
C解析代碼xmltest.c:
#include <libxml/parser.h> #include <libxml/tree.h> int main(int argc, char* argv[]) { xmlDocPtr doc; //定義解析文檔指針 xmlNodePtr curNode; //定義結點指針(你須要它爲了在各個結點間移動) xmlChar *szKey; //臨時字符串變量 char *szDocName; if (argc <= 1) { printf("Usage: %s docname/n", argv[0]); return(0); } szDocName = argv[1]; doc = xmlReadFile(szDocName,"GB2312",XML_PARSE_RECOVER); //解析文件 if (NULL == doc) { printf("Document not parsed successfully/n"); return -1; } curNode = xmlDocGetRootElement(doc); //肯定文檔根元素 if (NULL == curNode) { printf("empty document/n"); xmlFreeDoc(doc); return -1; } if (xmlStrcmp(curNode->name, BAD_CAST "ioMsg")) { printf("document of the wrong type, root node != ioMsg/n"); xmlFreeDoc(doc); return -1; } curNode = curNode->children; while(curNode != NULL) { //取出節點中的內容 szKey = xmlNodeGetContent(curNode); printf("Content value =%s/n", szKey); curNode = curNode->next; } xmlFreeDoc(doc); return 0; }
3. 編譯xml解析程序
假設Libxml2庫是按步驟1的編譯方式,其庫文件和頭文件分別位於/usr/local/lib和/usr/local/include/libxml2目錄下。
動態庫編譯方式: cc -o xmltest -I/usr/local/include/libxml2 -L/usr/local/lib -lxml2 xmltest.c |
「-I/usr/local/include/libxml2」指定Libxml2庫的頭文件所在的路徑,「-L/usr/local/lib」指定動態庫所在路徑。