libxml2剖析(3):使用教程

本文整理自官方使用教程http://xmlsoft.org/tutorial/index.html

    示例文檔story.xml如下:

  1. <?xml version="1.0"?>  
  2. <story>  
  3.   <storyinfo>  
  4.     <author>John Fleck</author>  
  5.     <datewritten>June 2, 2002</datewritten>  
  6.     <keyword>example keyword</keyword>  
  7.   </storyinfo>  
  8.   <body>  
  9.     <headline>This is the headline</headline>  
  10.     <para>This is the body text.</para>  
  11.   </body>  
  12. </story>  
    1、解析xml文檔
    解析文檔時只需要文檔名和一個函數調用,再加上錯誤處理。下面代碼查找keyword節點並打印節點下的文本內容,如下:
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #include <stdlib.h>  
  4. #include <libxml/xmlmemory.h>  
  5. #include <libxml/parser.h>  
  6.   
  7. /* 解析storyinfo節點,打印keyword節點的內容 */  
  8. void parseStory(xmlDocPtr doc, xmlNodePtr cur){  
  9.     xmlChar* key;  
  10.     cur=cur->xmlChildrenNode;  
  11.     while(cur != NULL){  
  12.         /* 找到keyword子節點 */  
  13.         if(!xmlStrcmp(cur->name, (const xmlChar *)"keyword")){  
  14.             key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);  
  15.             printf("keyword: %s\n", key);  
  16.             xmlFree(key);  
  17.         }  
  18.         cur=cur->next; /* 下一個子節點 */  
  19.     }  
  20.   
  21.     return;  
  22. }  
  23.   
  24. /* 解析文檔 */  
  25. static void parseDoc(char *docname){  
  26.     /* 定義文檔和節點指針 */  
  27.     xmlDocPtr doc;  
  28.     xmlNodePtr cur;  
  29.       
  30.     /* 進行解析,如果沒成功,顯示一個錯誤並停止 */  
  31.     doc = xmlParseFile(docname);  
  32.     if(doc == NULL){  
  33.         fprintf(stderr, "Document not parse successfully. \n");  
  34.         return;  
  35.     }  
  36.   
  37.     /* 獲取文檔根節點,若無內容則釋放文檔樹並返回 */  
  38.     cur = xmlDocGetRootElement(doc);  
  39.     if(cur == NULL){  
  40.         fprintf(stderr, "empty document\n");  
  41.         xmlFreeDoc(doc);  
  42.         return;  
  43.     }  
  44.   
  45.     /* 確定根節點名是否爲story,不是則返回 */  
  46.     if(xmlStrcmp(cur->name, (const xmlChar *)"story")){  
  47.         fprintf(stderr, "document of the wrong type, root node != story");  
  48.         xmlFreeDoc(doc);  
  49.         return;  
  50.     }  
  51.   
  52.     /* 遍歷文檔樹 */  
  53.     cur = cur->xmlChildrenNode;  
  54.     while(cur != NULL){  
  55.         /* 找到storyinfo子節點 */  
  56.         if(!xmlStrcmp(cur->name, (const xmlChar *)"storyinfo")){  
  57.             parseStory(doc, cur); /* 解析storyinfo子節點 */  
  58.         }  
  59.         cur = cur->next; /* 下一個子節點 */  
  60.     }  
  61.   
  62.     xmlFreeDoc(doc); /* 釋放文檔樹 */  
  63.     return;  
  64. }  
  65.   
  66. int main(int argc, char **argv){  
  67.     char *docname;  
  68.     if(argc <= 1){  
  69.         printf("Usage: %s docname\n", argv[0]);  
  70.         return 0;  
  71.     }  
  72.     docname=argv[1];  
  73.     parseDoc(docname);  
  74.     return 1;  
  75. }  
    解析XML文檔的基本流程如下:
    (1)定義文檔指針和節點指針。
    (2)調用xmlParseFile()解析文檔。如果不成功,註冊一個錯誤並停止。一個常見錯誤是不適當的編碼。XML標準文檔除了用默認的UTF-8或UTF-16外,還可顯式指定用其它編碼保存。如果文檔是這樣,libxml2將自動地爲你轉換到UTF-8。更多關於XML編碼信息包含在XML標準中。
    (3)調用xmlDocGetRootElement()獲取文檔根節點,若無根節點則釋放文檔樹並返回。
    (4)確認文檔是正確的類型,通過檢查根節點名稱來判斷。
    (5)檢索節點的內容,這需要遍歷文檔樹。對每個節點,遍歷其子節點都需要一個循環。先用cur = cur->xmlChildrenNode獲取第一個子節點,然後通過cur = cur->next不斷向前遍歷,直到cur==NULL。查找找指定節點時使用xmlStrcmp()函數,如果你指定的名稱相同,就找到了你要的節點。通常把查找某個子節點的過程封裝成函數。
    (6)獲取節點中的內容。查找到指定節點後,調用xmlNodeListGetString()獲取節點下的文本。注意在XML中,包含在節點中的文本是這個節點的子節點,因此獲取的是cur->xmlChildrenNode中的字符串。xmlNodeListGetString()會爲返回的字符串分配內存,因此記得要用xmlFree()來釋放它。
    (7)調用xmlFreeDoc()釋放文檔樹指針。
    2、使用XPath查詢信息
    在xml文檔中查詢信息是一項核心工作。Libxml2支持使用XPath表達式來查找匹配的節點集。簡而言之,XPath之於xml,好比SQL之於關係數據庫。要在一個複雜的xml文檔中查找所需的信息,XPath簡直是必不可少的工具。下面代碼查詢所有keyword元素的內容。
  1. #include <libxml/parser.h>  
  2. #include <libxml/xpath.h>  
  3.   
  4. /* 解析文檔 */  
  5. xmlDocPtr getdoc(char *docname){  
  6.     xmlDocPtr doc;  
  7.     doc = xmlParseFile(docname);  
  8.     if(doc == NULL){  
  9.         fprintf(stderr, "Document not parsed successfully. \n");  
  10.         return NULL;  
  11.     }  
  12.   
  13.     return doc;  
  14. }  
  15.   
  16. /* 查詢節點集 */  
  17. xmlXPathObjectPtr getnodeset(xmlDocPtr doc, xmlChar *xpath){  
  18.     xmlXPathContextPtr context;  
  19.     xmlXPathObjectPtr result; /* 存儲查詢結果 */  
  20.   
  21.     /* 創建一個xpath上下文 */  
  22.     context = xmlXPathNewContext(doc);  
  23.     if(context == NULL){  
  24.         printf("Error in xmlXPathNewContext\n");  
  25.         return NULL;  
  26.     }  
  27.     /* 查詢XPath表達式 */  
  28.     result = xmlXPathEvalExpression(xpath, context);  
  29.     xmlXPathFreeContext(context); /* 釋放上下文指針 */  
  30.     if(result == NULL){  
  31.         printf("Error in xmlXPathEvalExpression\n");  
  32.         return NULL;  
  33.     }  
  34.     /* 檢查結果集是否爲空 */  
  35.     if(xmlXPathNodeSetIsEmpty(result->nodesetval)){  
  36.         xmlXPathFreeObject(result); /* 如爲這空就釋放 */  
  37.         printf("No result\n");  
  38.         return NULL;  
  39.     }  
  40.     return result;  
  41. }  
  42.   
  43. int main(int argc, char ** argv){  
  44.     char *docname;  
  45.     xmlDocPtr doc;  
  46.     /* 查找所有keyword元素,而不管它們在文檔中的位置 */  
  47.     xmlChar *xpath=(xmlChar*)"//keyword";  
  48.     xmlNodeSetPtr nodeset;  
  49.     xmlXPathObjectPtr result;  
  50.     int i;  
  51.     xmlChar *keyword;  
  52.   
  53.     if(argc <= 1){  
  54.         printf("Usage: %s docname\n", argv[0]);  
  55.         return(0);  
  56.     }  
  57.   
  58.     docname = argv[1];  
  59.     doc = getdoc(docname);  
  60.     result = getnodeset(doc, xpath);  
  61.     if(result){  
  62.         /* 得到keyword節點集 */  
  63.         nodeset = result->nodesetval;  
  64.         for(i=0; i < nodeset->nodeNr; i++){ /* 打印每個節點中的內容 */  
  65.             keyword = xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode, 1);  
  66.             printf("keyword: %s\n", keyword);  
  67.             xmlFree(keyword);  
  68.         }  
  69.         xmlXPathFreeObject(result); /* 釋放結果集 */  
  70.     }  
  71.   
  72.     xmlFreeDoc(doc); /* 釋放文檔樹 */  
  73.     xmlCleanupParser(); /* 清除庫內存 */  
  74.     return(1);  
  75. }  
    可以在story.xml中多插入幾個keyword元素,然後運行一下本程序看看效果。使用XPath查詢信息的基本流程如下:
    (1)調用xmlXPathNewContext()給文檔樹創建一個上下文指針。
    (2)調用xmlXPathEvalExpression(),傳入XPath表達式和上下文指針,返回一個xmlXPathObjectPtr結果集指針。nodesetval對象包含keyword節點個數(nodeNr)和節點列表(nodeTab)。在使用之前要和xmlXPathNodeSetIsEmpty()檢查nodesetval節點列表是否爲空。
    (3)遍歷節點列表nodeTab,用xmlNodeListGetString()獲取每個keyword節點的內容。
    (4)用xmlXPathFreeObject()釋放查詢結果,用xmlFreeDoc()釋放文檔樹。
    更多關於Xpath的內容可以參考XPath官方規範http://www.w3.org/TR/xpath/。XPath語法的介紹,可參考w3school上的教程http://www.w3school.com.cn/xpath/index.asp,或者http://w3schools.com/xpath/default.asp。只有掌握XPath,才能掌握使用大型XML文件獲取信息的方法,否則每尋找一個節點都要從根節點找起,很耗時耗力。
    3、修改xml文檔
    這與上面的過程類似,首先遍歷文檔樹,找到要插入(或刪除)的節點處,然後插入(或刪除)相關的內容。下面代碼在storyinfo節點下插入一個keyword元素。
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #include <stdlib.h>  
  4. #include <libxml/xmlmemory.h>  
  5. #include <libxml/parser.h>  
  6.   
  7. void  
  8. parseStory(xmlDocPtr doc, xmlNodePtr cur, const xmlChar* keyword) {  
  9.     /* 在當前節點下插入一個keyword子節點 */  
  10.     xmlNewTextChild(cur, NULL, (const xmlChar*)"keyword", keyword);  
  11.     return;  
  12. }  
  13.   
  14. xmlDocPtr  
  15. parseDoc(char *docname, char *keyword) {  
  16.   
  17.     xmlDocPtr doc;  
  18.     xmlNodePtr cur;  
  19.   
  20.     doc = xmlParseFile(docname);  
  21.       
  22.     if (doc == NULL ) {  
  23.         fprintf(stderr,"Document not parsed successfully. \n");  
  24.         return (NULL);  
  25.     }  
  26.       
  27.     cur = xmlDocGetRootElement(doc);  
  28.       
  29.     if (cur == NULL) {  
  30.         fprintf(stderr,"empty document\n");  
  31.         xmlFreeDoc(doc);  
  32.         return (NULL);  
  33.     }  
  34.       
  35.     if (xmlStrcmp(cur->name, (const xmlChar *) "story")) {  
  36.         fprintf(stderr,"document of the wrong type, root node != story");  
  37.         xmlFreeDoc(doc);  
  38.         return (NULL);  
  39.     }  
  40.       
  41.     cur = cur->xmlChildrenNode;  
  42.     while (cur != NULL) {  
  43.         if ((!xmlStrcmp(cur->name, (const xmlChar *)"storyinfo"))){  
  44.             parseStory (doc, cur, (const xmlChar*)keyword);  
  45.         }  
  46.            
  47.     cur = cur->next;  
  48.     }  
  49.     return(doc);  
  50. }  
  51.   
  52. int  
  53. main(int argc, char **argv) {  
  54.   
  55.     char *docname;  
  56.     char *keyword;  
  57.     xmlDocPtr doc;  
  58.   
  59.     if (argc <= 2) {  
  60.         printf("Usage: %s docname, keyword\n", argv[0]);  
  61.         return(0);  
  62.     }  
  63.   
  64.     docname = argv[1];  
  65.     keyword = argv[2];  
  66.     doc = parseDoc(docname, keyword);  
  67.     if (doc != NULL) {  
  68.         xmlSaveFormatFile(docname, doc, 0);  
  69.         xmlFreeDoc(doc);  
  70.     }  
  71.       
  72.     return (1);  
  73. }  
    這裏xmlNewTextChild函數在當前節點指針上添加一個子元素。如果希望元素有名字空間,則可以在這裏加上。添加完後,就要用xmlSaveFormatFile()把修改後的文檔寫入到文件。我們這裏使用原來doc文檔指針,因此會覆蓋原來的文件。第三個參數如果設置爲1,則輸出的文檔會自動縮進。
    若要刪除某個節點,可以使用以下代碼:
  1. if(!xmlStrcmp(cur->name, BAD_CAST "keyword")){  
  2.     xmlNodePtr tempNode;  
  3.     tempNode = cur->next;  
  4.     xmlUnlinkNode(cur);  
  5.     xmlFreeNode(cur);  
  6.     cur = tempNode;  
  7.     continue;  
  8. }  
    注意libxml2並沒有xmlDelNode或者xmlRemoveNode之類的函數。我們需要將當前節點從文檔中斷鏈(unlink),文檔就不會再包含這個子節點。這樣做需要使用一個臨時變量來存儲斷鏈節點的後續節點,並記得要手動刪除斷鏈節點的內存。
    若要給節點添加屬性,可以這樣:
  1. xmlDocPtr  
  2. parseDoc(char *docname, char *uri) {  
  3.     xmlDocPtr doc;  
  4.     xmlNodePtr cur;  
  5.     xmlNodePtr newnode;  
  6.     xmlAttrPtr newattr;  
  7.   
  8.     doc = xmlParseFile(docname);      
  9.     if (doc == NULL ) {  
  10.         fprintf(stderr,"Document not parsed successfully. \n");  
  11.         return (NULL);  
  12.     }  
  13.       
  14.     cur = xmlDocGetRootElement(doc);      
  15.     if (cur == NULL) {  
  16.         fprintf(stderr,"empty document\n");  
  17.         xmlFreeDoc(doc);  
  18.         return (NULL);  
  19.     }  
  20.       
  21.     if (xmlStrcmp(cur->name, (const xmlChar *) "story")) {  
  22.         fprintf(stderr,"document of the wrong type, root node != story");  
  23.         xmlFreeDoc(doc);  
  24.         return (NULL);  
  25.     }  
  26.       
  27.     newnode = xmlNewTextChild(cur, NULL, "reference", NULL);  
  28.     newattr = xmlNewProp(newnode, "uri", uri);  
  29.     return(doc);  
  30. }  
    我們用xmlAttrPtr聲明一個屬性指針。在找到story元素後,用xmlNewTextChild()新建一個reference子元素,用xmlNewProp()給這個子元素新建一個uri屬性。文檔修改完後要用xmlSaveFormatFile()寫入到磁盤。
    查詢屬性的過程類似。如下:
  1. void  
  2. getReference(xmlDocPtr doc, xmlNodePtr cur) {  
  3.     xmlChar *uri;  
  4.     cur = cur->xmlChildrenNode;  
  5.     while (cur != NULL) {  
  6.         if ((!xmlStrcmp(cur->name, (const xmlChar *)"reference"))) {  
  7.             uri = xmlGetProp(cur, "uri");  
  8.             printf("uri: %s\n", uri);  
  9.             xmlFree(uri);  
  10.         }  
  11.         cur = cur->next;  
  12.     }  
  13.     return;  
  14. }  
    關鍵函數爲xmlGetProp(),用來獲取節點中的指定屬性。注意如果你使用DTD爲屬性聲明一個固定的或默認的值,則該函數也查找這些值。
    4、創建xml文檔
    有了上面的基礎,創建一個xml文檔顯得非常簡單,就是一個不斷插入節點的過程。其流程如下:
    (1)用xmlNewDoc函數創建一個文檔指針doc;
    (2)用xmlNewNode函數創建一個節點指針root_node;
    (3)用xmlDocSetRootElement將root_node設置爲doc的根結點;
    (4)用xmlAddChild()給root_node添加一系列的子節點,並設置子節點的內容和屬性;
    (5)用xmlSaveFile將xml文檔存入文件;
    (6)用xmlFreeDoc函數關閉文檔指針,並清除本文檔中所有節點動態申請的內存。    
    下面代碼創建一個xml文檔:
  1. #include <stdio.h>  
  2. #include <iostream>  
  3. #include <libxml/parser.h>  
  4. #include <libxml/tree.h>  
  5. using namespace std;  
  6.   
  7. int main(int argc, char* argv[]){  
  8.     //定義文檔和節點指針  
  9.     xmlDocPtr doc=xmlNewDoc(BAD_CAST"1.0");  
  10.     xmlNodePtr root_node=xmlNewNode(NULL,BAD_CAST"root");  
  11.     //設置根節點  
  12.     xmlDocSetRootElement(doc,root_node);  
  13.     //在根節點中直接創建節點  
  14.     xmlNewTextChild(root_node, NULL, BAD_CAST"newNode1", BAD_CAST"newNode1 content");  
  15.     xmlNewTextChild(root_node, NULL, BAD_CAST"newNode2", BAD_CAST"newNode2 content");  
  16.     xmlNewTextChild(root_node, NULL, BAD_CAST"newNode3", BAD_CAST"newNode3 content");  
  17.     //創建一個節點,設置其內容和屬性,然後加入根結點  
  18.     xmlNodePtr node=xmlNewNode(NULL, BAD_CAST"node2");  
  19.     xmlNodePtr content=xmlNewText(BAD_CAST"NODE CONTENT");  
  20.     xmlAddChild(root_node,node);  
  21.     xmlAddChild(node,content);  
  22.     xmlNewProp(node,BAD_CAST"attribute",BAD_CAST"yes");  
  23.     //創建一個兒子和孫子節點  
  24.     node=xmlNewNode(NULL,BAD_CAST"son");  
  25.     xmlAddChild(root_node,node);  
  26.     xmlNodePtr grandson=xmlNewNode(NULL,BAD_CAST"grandson");  
  27.     xmlAddChild(node,grandson);  
  28.     xmlAddChild(grandson,xmlNewText(BAD_CAST"This is a grandson node"));  
  29.     //存儲xml文檔  
  30.     int nRel=xmlSaveFile("CreatedXml.xml",doc);  
  31.     if(nRel!=-1){  
  32.         cout<<"一個xml文檔被創建,寫入"<<nRel<<"個字節"<<endl;  
  33.     }  
  34.     //釋放文檔內節點動態申請的內存  
  35.     xmlFreeDoc(doc);  
  36.     return 1;  
  37. }  
    編譯並運行這個程序,將創建CreatedXml.xml文檔,內容如下:
  1. <root>  
  2.     <newNode1>newNode1 content</newNode1>  
  3.     <newNode2>newNode2 content</newNode2>  
  4.     <newNode3>newNode3 content</newNode3>  
  5.     <node2 attribute="yes">NODE CONTENT</node2>  
  6.     <son>  
  7.         <grandson>This is a grandson node</grandson>  
  8.     </son>  
  9. </root>  
    注意,有多種方式可以添加子節點。第一是用xmlNewTextChild直接添加一個文本子節點;第二是先創建新節點,然後用xmlAddChild將新節點加入上層節點。
    5、編碼轉換
    數據編碼兼容性問題是很多開發人員都會遇到的一大難題,特別是在使用libxml時。libxml內部使用UTF-8格式存儲和操作數據。你的應用程序數據如果使用其他格式的編碼,例如ISO-8859-1編碼,則在傳給libxml之前必須轉換成UTF-8格式。如果你的應用輸出想用非UTF-8格式的編碼,也需要進行轉換。
    Libxml2本身只支持把UTF-8, UTF-16和ISO-8859-1格式的外部數據轉換成內部使用的UTF-8格式,以及處理完後輸出成這些格式的數據。對其他的字符編碼,需要使用libiconv(當然你也可以使用其他的國際化庫,例如ICU)。當前libiconv支持150多種不同的字符編碼,libiconv的實現儘量保證支持所有我們聽過的編碼格式。在使用libxml之前,一般是通過libiconv把數據先轉換UTF-8格式。在使用libxml處理完之後,再通過libiconv把數據輸出成你要的編碼格式。
    一個常見的錯誤是一份代碼的不同部分的數據使用不同的編碼格式。例如內部數據使用ISO-8859-1格式的應用程序,聯合使用libxml,而它的內部數據格式爲UTF-8。這樣應用程序在運行不同的代碼段時要不同地對待內部數據,這有可能導致解析數據出現錯誤。
    例子1:使用Libxml內建的編碼處理器
    下面的例子創建一個簡單的文檔,添加從命令行得到的數據到文檔根元素,並以合適的編碼格式輸出到stdout。對提供的數據我們使用ISO-8859-1編碼,處理過程爲從ISO-8859-1到UTF-8,再到ISO-8859-1。命令行上輸入的字符串從ISO-8859-1格式轉換成UTF-8格式,以供libxml使用,輸出時又重新轉換成ISO-8859-1格式。
  1. #include <string.h>  
  2. #include <libxml/parser.h>  
  3.   
  4. /* 對指定編碼格式的外部數據,轉換成libxml使用UTF-8格式 */  
  5. unsigned char*  
  6. convert(unsigned char *in, char *encoding){  
  7.     unsigned char *out;  
  8.     int ret,size,out_size,temp;  
  9.     /* 定義一個編碼處理器指針 */  
  10.     xmlCharEncodingHandlerPtr handler;  
  11.   
  12.     size = (int)strlen((const char*)in)+1; /* 輸入數據長度 */  
  13.     out_size = size*2-1; /* 輸出數據長度 */  
  14.     out = (unsigned char*)malloc((size_t)out_size); /* 存放輸出數據 */  
  15.   
  16.     if (out) {  
  17.         /* 查找內建的編碼處理器 */  
  18.         handler = xmlFindCharEncodingHandler(encoding);  
  19.         if(!handler) {  
  20.             free(out);  
  21.             out = NULL;  
  22.         }  
  23.     }  
  24.     if(out) {  
  25.         temp=size-1;  
  26.         /* 對輸入數據進行編碼轉換 */  
  27.         ret = handler->input(out, &out_size, in, &temp);  
  28.         if(ret || temp-size+1) { /* 轉換不成功 */  
  29.             if (ret) { /* 轉換失敗 */  
  30.                 printf("conversion wasn't successful.\n");  
  31.             } else { /* 只轉換了一部分數據 */  
  32.                 printf("conversion wasn't successful. converted: %i octets.\n",temp);  
  33.             }  
  34.             free(out);  
  35.             out = NULL;  
  36.         }else { /* 轉換成功 */  
  37.             out = (unsigned char*)realloc(out,out_size+1);  
  38.             out[out_size]=0; /* 輸出的末尾加上null終止符 */  
  39.                           
  40.         }  
  41.     } else {  
  42.         printf("no mem\n");  
  43.     }  
  44.     return (out);  
  45. }     
  46.   
  47. int  
  48. main(int argc, char **argv) {  
  49.     unsigned char *content, *out;  
  50.     xmlDocPtr doc;  
  51.     xmlNodePtr rootnode;  
  52.     char *encoding = "ISO-8859-1";  
  53.       
  54.     if (argc <= 1) {  
  55.         printf("Usage: %s content\n", argv[0]);  
  56.         return(0);  
  57.     }  
  58.   
  59.     content = (unsigned char*)argv[1];  
  60.     /* 轉換成libxml2使用的UTF-8格式 */  
  61.     out = convert(content, encoding);  
  62.     doc = xmlNewDoc (BAD_CAST "1.0");  
  63.     rootnode = xmlNewDocNode(doc, NULL, (const xmlChar*)"root", out);  
  64.     xmlDocSetRootElement(doc, rootnode);  
  65.     /* 以ISO-8859-1格式輸出文檔內容 */  
  66.     xmlSaveFormatFileEnc("-", doc, encoding, 1);  
  67.     return (1);  
  68. }  
    編譯運行這個程序,假設在命令行上提供的數據"zhou"是ISO-8859-1格式(我的系統中不是),則輸出文檔爲:
  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2. <root>zhou</root>  
    編碼轉換的基本流程如下:
    (1)用xmlCharEncodingHandlerPtr定義一個編碼處理器指針,用xmlFindCharEncodingHandler()查找libxml2中指定的編碼處理器。libxml2內建只支持把UTF-8, UTF-16和ISO-8859-1格式的外部數據轉換成內部使用的UTF-8格式。如果要轉換其他格式的數據(如中文編碼),則要使用獨立的libiconv庫給libxml2註冊新編碼處理器。
    (2)調用編碼處理器的input()函數,把外部數據轉換成libxml2使用的格式。
    (3)進行xml處理,處理完若要保存成非UTF-8格式的文檔,使用xmlSaveFormatFileEnc()函數。若保存的編碼格式libxml2不支持,則只能用libiconv把保存的文檔轉換成需要的編碼格式。
    例子2:通過iconv庫給Libxml註冊新的編碼處理器    
    下面例子先編寫GBK的編碼處理器gbk_input()和gbk_output(),前者是GBK到UTF-8輸入處理,後者是UTF-8到GBK輸出處理,這兩個處理器都要用到iconv轉換函數。然後調用xmlNewCharEncodingHandler()註冊輸入輸出處理器。對輸入輸出數據的編碼轉換由convertToUTF8From()和utf8ConvertTo()來完成,它們都是調用xmlFindCharEncodingHandler()查找已註冊的處理器,然後在處理器上調用input()或output()對數據進行編碼轉換。
  1. #include <string.h>  
  2. #include <iconv.h>  
  3. #include <libxml/encoding.h>  
  4. #include <libxml/xmlwriter.h>  
  5. #include <libxml/xmlreader.h>  
  6.   
  7. /* 輸入編碼處理器:GBK到UTF-8 */  
  8. int gbk_input(unsigned char *out, int *outlen,   
  9.         const unsigned char *in, int *inlen){  
  10.   
  11.     char *outbuf = (char *) out;  
  12.     char *inbuf = (char *) in;  
  13.     iconv_t iconv_from; /* gbk到utf-8的轉換描述符 */  
  14.     size_t len1, len2, rslt;  
  15.     /* 注意一般不直接從int*到size_t*的轉換 
  16.        這在32位平臺下是正常的,但到了64平臺下size_t爲64位, 
  17.        那(size_t*)inlen將是一個未知的數據  
  18.     */  
  19.     len1 = *inlen;  
  20.     len2 = *outlen;  
  21.     /* 分配一個從GBK到UTF-8的轉換描述符 */  
  22.     iconv_from = iconv_open("utf-8","gbk");  
  23.     /* 根據轉換描述符,對數據進行編碼轉換 */  
  24.     rslt = iconv(iconv_from, &inbuf, &len1, &outbuf, &len2);  
  25.     if(rslt < 0){  
  26.         return rslt;  
  27.     }  
  28.     iconv_close(iconv_from); /* 釋放描述符 */  
  29.     *outlen = ((unsigned char *) outbuf - out);  
  30.     *inlen = ((unsigned char *) inbuf - in);  
  31.     return *outlen;  
  32. }  
  33.   
  34. /* 輸出編碼處理器:UTF-8到GBK */  
  35. int gbk_output(unsigned char *out, int *outlen,   
  36.                 const unsigned char *in, int *inlen){  
  37.   
  38.     char *outbuf = (char *) out;  
  39.     char *inbuf = (char *) in;  
  40.     iconv_t iconv_to; /* utf-8到gbk的轉換描述符 */  
  41.     size_t len1, len2, rslt;  
  42.     /* 注意一般不直接從int*到size_t*的轉換 
  43.        這在32位平臺下是正常的,但到了64平臺下size_t爲64位, 
  44.        那(size_t*)inlen將是一個未知的數據  
  45.     */  
  46.     len1 = *inlen;  
  47.     len2 = *outlen;  
  48.     /* 分配一個從UTF-8到GBK的轉換描述符 */  
  49.     iconv_to=iconv_open("gbk","utf-8");  
  50.     /* 根據轉換描述符,對數據進行編碼轉換 */  
  51.     rslt = iconv(iconv_to, &inbuf, &len1, &outbuf, &len2);  
  52.     if(rslt < 0){  
  53.         return rslt;  
  54.     }  
  55.     iconv_close(iconv_to); /* 釋放描述符 */  
  56.     *outlen = ((unsigned char *) outbuf - out);  
  57.     *inlen = ((unsigned char *) inbuf - in);  
  58.     return *outlen;  
  59. }  
  60.   
  61. /** 
  62.  * convertToUTF8From: 
  63.  * 把encoding編碼的輸入數據in轉換成utf-8格式返回 
  64.  * 出錯則返回NULL 
  65.  */  
  66. xmlChar *convertToUTF8From(const char *in, const char *encoding){  
  67.     xmlChar *out;  
  68.     int ret;  
  69.     int size;  
  70.     int out_size;  
  71.     int temp;  
  72.     xmlCharEncodingHandlerPtr handler;  
  73.     if (in == 0)  
  74.         return 0;  
  75.     /* 查找內建的編碼處理器 */  
  76.     handler = xmlFindCharEncodingHandler(encoding);  
  77.     if (!handler) {  
  78.         printf("convertToUTF8From: no encoding handler found for '%s'\n",  
  79.                encoding ? encoding : "");  
  80.         return 0;  
  81.     }  
  82.     size = (int)strlen(in) + 1;  /* 輸入數據長度 */  
  83.     out_size = size*2 - 1;  /* 輸出數據長度 */  
  84.     /* 存放輸出數據 */  
  85.     out = (unsigned char *) xmlMalloc((size_t) out_size);  
  86.     memset(out, 0, out_size);  
  87.   
  88.     if(out != NULL) {  
  89.         temp = size - 1;  
  90.         /* 對輸入數據進行編碼轉換,成功後返回0 */  
  91.         ret = handler->input(out, &out_size, (const xmlChar *) in, &temp);  
  92.         if(ret || temp - size + 1) {  /* 轉換不成功 */  
  93.             if(ret){  /* 轉換失敗 */  
  94.                 printf("convertToUTF8From: conversion wasn't successful.\n");  
  95.             }else{  /* 只轉換了一部分數據 */  
  96.                 printf("convertToUTF8From: conversion wasn't successful. converted: %i octets.\n", temp);  
  97.             }  
  98.             xmlFree(out); /* 釋放輸出緩衝區 */  
  99.             out = 0;  
  100.         }else{  /* 轉換成功,在輸出末尾加上null終止符 */  
  101.             out = (unsigned char *) xmlRealloc(out, out_size + 1);  
  102.             out[out_size] = 0;  
  103.         }  
  104.     } else {  
  105.         printf("convertToUTF8From: no mem\n");  
  106.     }  
  107.     return out;  
  108. }  
  109.   
  110. /** 
  111.  * utf8ConvertTo: 
  112.  * 把utf-8的數據轉換成encoding編碼返回 
  113.  * 出錯則返回NULL 
  114.  */  
  115. char *utf8ConvertTo(xmlChar *in, const char *encoding){  
  116.     char *out;  
  117.     int ret;  
  118.     int size;  
  119.     int out_size;  
  120.     int temp;  
  121.     xmlCharEncodingHandlerPtr handler;  
  122.   
  123.     if (in == 0)  
  124.         return 0;  
  125.   
  126.     handler = xmlFindCharEncodingHandler(encoding);  
  127.   
  128.     if (!handler) {  
  129.         printf("utf8ConvertTo: no encoding handler found for '%s'\n",  
  130.                encoding ? encoding : "");  
  131.         return 0;  
  132.     }  
  133.   
  134.     size = (int) strlen((char*)in) + 1;  /* 輸入數據長度 */  
  135.     out_size = size * 2 - 1;  /* 輸出數據長度 */  
  136.     out = (char *) malloc((size_t) out_size);  /* 存放輸出數據 */  
  137.     memset(out,0,out_size);  
  138.     if(out != NULL) {  
  139.         temp = size - 1;  
  140.         /* 對輸入數據進行編碼轉換,成功後返回0 */  
  141.         ret = handler->output((xmlChar*)out, &out_size, (const xmlChar *) in, &temp);  
  142.         if(ret || temp - size + 1){  
  143.             if(ret){  
  144.                 printf("utf8ConvertTo: conversion wasn't successful.\n");  
  145.             }else{  
  146.                 printf("utf8ConvertTo: conversion wasn't successful. converted: %i octets.\n", temp);  
  147.             }  
  148.             free(out);  
  149.             out = 0;  
  150.         }else{  
  151.             out = (char *) realloc(out, out_size + 1);  
  152.             out[out_size] = 0;  /* 末尾加上null終止符 */  
  153.         }  
  154.     }else{  
  155.         printf("utf8ConvertTo: no mem\n");  
  156.     }  
  157.   
  158.     return out;  
  159. }  
  160.   
  161. int main(int argc, char **argv){  
  162.     const char *content;  
  163.     xmlChar *out;  
  164.     xmlDocPtr doc;  
  165.     xmlNodePtr rootnode;  
  166.       
  167.     if (argc <= 1) {  
  168.         printf("Usage: %s content\n", argv[0]);  
  169.         return(0);  
  170.     }  
  171.     content = (const char*)argv[1];  
  172.   
  173.     /* 添加gbk編碼支持 */  
  174.     xmlNewCharEncodingHandler("gbk", gbk_input, gbk_output);  
  175.     /* 添加gb2312編碼支持:仍然可以使用GBK的輸入輸出處理器 */  
  176.     xmlNewCharEncodingHandler("gb2312", gbk_input, gbk_output);  
  177.   
  178.     /* 輸入的GBK數據轉換成libxml2使用的UTF-8格式 */  
  179.     out = convertToUTF8From(content, "gbk");  
  180.     /* 創建xml文檔 */  
  181.     doc = xmlNewDoc(BAD_CAST "1.0");  
  182.     rootnode = xmlNewDocNode(doc, NULL, (const xmlChar*)"root", out);  
  183.     xmlDocSetRootElement(doc, rootnode);  
  184.     /* 以gb2312格式保存文檔內容:"-"表示輸出到終端 */  
  185.     xmlSaveFormatFileEnc("-", doc, "gb2312", 1);  
  186.       
  187.     xmlCleanupCharEncodingHandlers();/* 釋放編碼處理器資源 */  
  188.     return (1);  
  189. }  
    這個例子在32位與64位Linux平臺下測試通過。iconv庫是Linux默認自帶的組件,因此在Linux中使用libxml非常方便。我們先建立utf-8編碼與gbk編碼的轉換接口,並將接口插入到libxml2庫中,這樣xml庫就支持對gb2312和gbk編碼的支持了。當然,這個轉換不會自動完成,我們需要使用從libxml庫中查找特定編碼的接口,libxml支持一些基本的編碼接口,如ISO-8859-1,UTF-16等編碼,但不支持gbk,所以在上述代碼中,我們定義了gbk_input,與gbk_output兩個接口,這兩個接口的原型聲明是libxml庫的標準聲明,即xmlCharEncodingInputFunc和xmlCharEncodingOutputFunc。在使用完libxml庫之後,我們需要釋放libxml庫的轉換資源。
    例子3:直接使用iconv庫進行轉換
    下面例子直接使用iconv函數對輸入輸出進行編碼轉換,而不是通過註冊編碼處理器的方式。
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #include <iconv.h>  
  4. #include <libxml/parser.h>  
  5. #include <libxml/tree.h>  
  6.   
  7. /* 代碼轉換:從一種編碼轉爲另一種編碼 */  
  8. int encoding_convert(const char *from_charset, const char *to_charset,   
  9.             char *inbuf, int inlen,   
  10.             char* outbuf, int outlen){  
  11.   
  12.     iconv_t cd;  
  13.     size_t len1, len2, rslt;  
  14.   
  15.     /* 注意一般不直接從int*到size_t*的轉換 
  16.        這在32位平臺下是正常的,但到了64平臺下size_t爲64位, 
  17.        那(size_t*)inlen將是一個未知的數據  
  18.     */  
  19.     len1 = inlen;  
  20.     len2 = outlen;  
  21.     /* 分配一個轉換描述符 */  
  22.     cd = iconv_open(to_charset,from_charset);  
  23.     if(cd == 0)  
  24.        return -1;  
  25.     memset(outbuf,0,len2);   
  26.     /* 執行編碼轉換 */  
  27.     rslt=iconv(cd, &inbuf, &len1, &outbuf, &len2);  
  28.     if(rslt== -1)  
  29.         return -1;    
  30.   
  31.     iconv_close(cd); /* 釋放描述符 */  
  32.     return 0;    
  33.   
  34. }  
  35.   
  36. /* GB2312轉換爲UTF-8  
  37.  * 成功則返回一個動態分配的char*變量,需要在使用完畢後手動free,失敗返回NULL 
  38.  */  
  39. char *gb2312_utf8(char *inbuf){  
  40.     int nOutLen = 2*strlen(inbuf)-1;  
  41.     char *szOut=(char*)xmlMalloc(nOutLen);  
  42.     if(-1 == encoding_convert("gb2312","uft-8",inbuf,strlen(inbuf),szOut,nOutLen)){  
  43.         xmlFree(szOut);  
  44.         szOut=NULL;  
  45.     }  
  46.     return szOut;  
  47. }  
  48.   
  49. /* UTF-8轉換爲GB2312 
  50.  * 成功則返回一個動態分配的char*變量,需要在使用完畢後手動free,失敗返回NULL 
  51.  */  
  52. char *utf8_gb2312(char *inbuf){  
  53.     int nOutLen = 2* strlen(inbuf)-1;  
  54.     char *szOut=(char*)xmlMalloc(nOutLen);  
  55.     if(-1 == encoding_convert("utf-8","gb2312",inbuf,strlen(inbuf),szOut,nOutLen)){  
  56.         xmlFree(szOut);  
  57.         szOut=NULL;  
  58.     }  
  59.     return szOut;  
  60. }  
  61.   
  62. int main(int argc, char **argv){  
  63.     /* 定義文檔節點和指針 */  
  64.     xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");  
  65.     xmlNodePtr root_node=xmlNewNode(NULL, BAD_CAST "root");  
  66.     /* 設置根節點 */  
  67.     xmlDocSetRootElement(doc, root_node);  
  68.   
  69.     /* 一箇中文字符串轉換爲UTF-8字符串,然後寫入 */  
  70.     char *szOut=gb2312_utf8("節點1的內容");  
  71.     /* 在根節點中直接創建節點 */  
  72.     xmlNewTextChild(root_node, NULL, BAD_CAST "newNode1", BAD_CAST "newNode1 content");  
  73.     xmlNewTextChild(root_node, NULL, BAD_CAST "newNode2", BAD_CAST "newNode2 content");  
  74.     xmlNewTextChild(root_node, NULL, BAD_CAST "newNode3", BAD_CAST "newNode3 content");  
  75.     xmlNewChild(root_node, NULL, BAD_CAST "node1",BAD_CAST szOut);  
  76.     xmlFree(szOut);  
  77.   
  78.     /* 創建一個節點,設置其內容和屬性,然後加入根結點 */  
  79.     xmlNodePtr node = xmlNewNode(NULL,BAD_CAST "node2");  
  80.     xmlNodePtr content = xmlNewText(BAD_CAST "NODE CONTENT");  
  81.     xmlAddChild(root_node,node);  
  82.     xmlAddChild(node,content);  
  83.     szOut = gb2312_utf8("屬性值");  
  84.     xmlNewProp(node,BAD_CAST "attribute",BAD_CAST szOut);  
  85.     xmlFree(szOut);  
  86.   
  87.     /* 創建一箇中文節點 */  
  88.     szOut = gb2312_utf8("中文節點");  
  89.     xmlNewChild(root_node, NULL, BAD_CAST szOut,BAD_CAST "content of chinese node");  
  90.     xmlFree(szOut);  
  91.   
  92.     /* 存儲xml文檔 */  
  93.     int nRel = xmlSaveFormatFileEnc("CreatedXml_cn.xml",doc,"GB2312",1);  
  94.     if (nRel != -1){  
  95.         printf("一個xml文檔被創建,寫入%d個字節", nRel);  
  96.     }  
  97.   
  98.     xmlFreeDoc(doc);  
  99.     return 1;  
  100. }  
    這個例子中,當把中文數據寫入到XML節點時,使用gb2312_utf8()直接轉換成UTF-8格式,這種直接通過iconv轉換的方式更高效。編譯並運行程序,輸出文檔如下:
  1. <?xml version="1.0" encoding="GB2312"?>  
  2. <root>  
  3.     <newNode1>newNode1 content</newNode1>  
  4.     <newNode2>newNode2 content</newNode2>  
  5.     <newNode3>newNode3 content</newNode3>  
  6.     <node1>節點1的內容</node1>  
  7.     <node2 attribute="屬性值">NODE CONTENT</node2>  
  8.     <中文節點>content of chinese node</中文節點>  
  9. </root>     
    6、一個真實的例子
    內容整理自http://xmlsoft.org/example.html
    下面是一個真實的例子。應用程序數據的內容不使用DOM樹,而是使用內部數據結構來保存。這是一個基於XML存儲結構的數據庫,它保存了與Gnome相關的任務。如下:
  1. <?xml version="1.0"?>  
  2. <gjob:Helping xmlns:gjob="http://www.gnome.org/some-location">  
  3.   <gjob:Jobs>  
  4.   
  5.     <gjob:Job>  
  6.       <gjob:Project ID="3"/>  
  7.       <gjob:Application>GBackup</gjob:Application>  
  8.       <gjob:Category>Development</gjob:Category>  
  9.   
  10.       <gjob:Update>  
  11.         <gjob:Status>Open</gjob:Status>  
  12.         <gjob:Modified>Mon, 07 Jun 1999 20:27:45 -0400 MET DST</gjob:Modified>  
  13.         <gjob:Salary>USD 0.00</gjob:Salary>  
  14.       </gjob:Update>  
  15.   
  16.       <gjob:Developers>  
  17.         <gjob:Developer>  
  18.         </gjob:Developer>  
  19.       </gjob:Developers>  
  20.   
  21.       <gjob:Contact>  
  22.         <gjob:Person>Nathan Clemons</gjob:Person>  
  23.         <gjob:Email>[email protected]</gjob:Email>  
  24.         <gjob:Company>  
  25.         </gjob:Company>  
  26.         <gjob:Organisation>  
  27.         </gjob:Organisation>  
  28.         <gjob:Webpage>  
  29.         </gjob:Webpage>  
  30.         <gjob:Snailmail>  
  31.         </gjob:Snailmail>  
  32.         <gjob:Phone>  
  33.         </gjob:Phone>  
  34.       </gjob:Contact>  
  35.   
  36.       <gjob:Requirements>  
  37.       The program should be released as free software, under the GPL.  
  38.       </gjob:Requirements>  
  39.   
  40.       <gjob:Skills>  
  41.       </gjob:Skills>  
  42.   
  43.       <gjob:Details>  
  44.       A GNOME based system that will allow a superuser to configure   
  45.       compressed and uncompressed files and/or file systems to be backed   
  46.       up with a supported media in the system.  This should be able to   
  47.       perform via find commands generating a list of files that are passed   
  48.       to tar, dd, cpio, cp, gzip, etc., to be directed to the tape machine   
  49.       or via operations performed on the filesystem itself. Email   
  50.       notification and GUI status display very important.  
  51.       </gjob:Details>  
  52.   
  53.     </gjob:Job>  
  54.   
  55.   </gjob:Jobs>  
  56. </gjob:Helping>  
    把XML文件加載到一個內部DOM樹中只是調用幾個函數的問題,而遍歷整個樹來收集數據,並生成內部結構則更困難,也更容易出錯。
    對輸入結構的定義法則是非常寬鬆的。屬性的順序無關緊要(XML規範清楚地說明了這一點),不要依賴於一個節點的子節點順序通常是一個好的主意,除非這樣做真的使事情變得更困難了。下面是解析person信息的一段代碼:
  1. /* 
  2.  * 一個person記錄 
  3.  */  
  4. typedef struct person {  
  5.     char *name;  
  6.     char *email;  
  7.     char *company;  
  8.     char *organisation;  
  9.     char *smail;  
  10.     char *webPage;  
  11.     char *phone;  
  12. } person, *personPtr;  
  13.   
  14. /* 
  15.  * 解析person的代碼 
  16.  */  
  17. personPtr parsePerson(xmlDocPtr doc, xmlNsPtr ns, xmlNodePtr cur) {  
  18.     personPtr ret = NULL;  
  19.   
  20. DEBUG("parsePerson\n");  
  21.     /* 
  22.      * 爲結構分配內存 
  23.      */  
  24.     ret = (personPtr) malloc(sizeof(person));  
  25.     if (ret == NULL) {  
  26.         fprintf(stderr,"out of memory\n");  
  27.         return(NULL);  
  28.     }  
  29.     memset(ret, 0, sizeof(person));  
  30.   
  31.     /* 我們不關心頂層的元素名是什麼 */  
  32.     cur = cur->xmlChildrenNode;  
  33.     while (cur != NULL) {  
  34.         if ((!strcmp(cur->name, "Person")) && (cur->ns == ns))  
  35.             ret->name = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);  
  36.         if ((!strcmp(cur->name, "Email")) && (cur->ns == ns))  
  37.             ret->email = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);  
  38.         cur = cur->next;  
  39.     }  
  40.   
  41.     return(ret);  
  42. }  
    下面是要注意的一些事項:
    (1)通常一個遞歸的解析風格是更方便的:XML數據天然地遵循重複式地構造,並且是高度結構化的。
    (2)兩個參數是xmlDocPtr和xmlNsPtr類型,即指向XML文檔和應用程序保留的命名空間的指針。文檔信息非常廣泛,爲你的應用程序數據集定義一個命名空間並測試元素和屬性是否屬性這個空間是一個好的編程實踐。這隻需一個簡單的相等測試(cur->ns == ns)。
    (3)爲了查詢文本和屬性值,你可以使用函數xmlNodeListGetString()來獲取所有文本,和由DOM輸出生成的引用節點,並生成一個單一的文本字符串。
    下面是解析另外一個結構的代碼片段:
  1. #include <libxml/tree.h>  
  2. /* 
  3.  * 一個Job的描述 
  4.  */  
  5. typedef struct job {  
  6.     char *projectID;  
  7.     char *application;  
  8.     char *category;  
  9.     personPtr contact;  
  10.     int nbDevelopers;  
  11.     personPtr developers[100]; /* using dynamic alloc is left as an exercise */  
  12. } job, *jobPtr;  
  13.   
  14. /* 
  15.  * 解析Job的代碼 
  16.  */  
  17. jobPtr parseJob(xmlDocPtr doc, xmlNsPtr ns, xmlNodePtr cur) {  
  18.     jobPtr ret = NULL;  
  19.   
  20. DEBUG("parseJob\n");  
  21.     /* 
  22.      * 爲結構分配內存 
  23.      */  
  24.     ret = (jobPtr) malloc(sizeof(job));  
  25.     if (ret == NULL) {  
  26.         fprintf(stderr,"out of memory\n");  
  27.         return(NULL);  
  28.     }  
  29.     memset(ret, 0, sizeof(job));  
  30.   
  31.     /* 我們不關心頂層元素名是什麼 */  
  32.     cur = cur->xmlChildrenNode;  
  33.     while (cur != NULL) {  
  34.           
  35.         if ((!strcmp(cur->name, "Project")) && (cur->ns == ns)) {  
  36.             ret->projectID = xmlGetProp(cur, "ID");  
  37.             if (ret->projectID == NULL) {  
  38.                 fprintf(stderr, "Project has no ID\n");  
  39.             }  
  40.         }  
  41.         if ((!strcmp(cur->name, "Application")) && (cur->ns == ns))  
  42.             ret->application = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);  
  43.         if ((!strcmp(cur->name, "Category")) && (cur->ns == ns))  
  44.             ret->category = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);  
  45.         if ((!strcmp(cur->name, "Contact")) && (cur->ns == ns))  
  46.             ret->contact = parsePerson(doc, ns, cur);  
  47.         cur = cur->next;  
  48.     }  
  49.   
  50.     return(ret);  
  51. }  

    一旦你會使用libxml2,編寫這種類型的代碼是非常簡單的,也很無趣。最終,你可以寫一個擁有C數據結構和一組XML文檔例子或一個XML DTD的樁模塊,並生成在C數據和XML存儲之間導入和導出數據的代碼。

    7、詳細代碼示例
    對Libxml2更詳細的使用介紹,可參考官方的詳細代碼示例http://xmlsoft.org/examples/index.html。上面提供了Libxml2各個組件怎麼使用的詳細代碼示例,包括以下部分:
    xmlWriter: 測試xmlWriter的各個API,包括寫入到文件、寫入到內存緩衝區、寫入到新的文檔或子樹、字符串編碼轉換、對輸出文檔進行序列化。
    InputOutput: 演示使用xmlRegisterInputCallbacks來建立一個客戶I/O層,這被用在XInclude方法上下文中,以顯示怎樣構建動態文檔。還演示使用xmlDocDumpMemory來輸出文檔到字符緩衝區中。
    Parsing: 演示使用xmlReadMemory()讀取XML文檔,xmlFreeDoc()釋放文檔樹;使用xmlCreatePushParserCtxt()和xmlParseChunk()一塊一塊地讀取XML文檔到文檔樹中。演示爲XML文檔創建一個解析上下文,然後解析並驗證這個文檔;創建一個文檔樹,檢查並驗證結果,最後用xmlFreeDoc()釋放文檔樹。演示使用xmlReadFile()讀取XML文檔並用xmlFreeDoc()釋放它。
    Tree: 演示怎樣創建文檔和節點,並把數據dump到標準輸出或文件中。演示使用xmlDocGetRootElement()獲取根元素,然後遍歷文檔並打印各個元素名。
    XPath: 演示怎樣計算XPath表達式,並在XPath上下文註冊名稱空間,打印結果節點集。演示怎麼加載一個文檔、用XPath定位到某個子元素、修改這個元素並保存結果。這包含了加載/編輯/保存的一個完整來回。
    xmlReader: 演示使用xmlReaderForFile()解析XML文檔,並dump出節點的信息。演示在用xmlReaderForFile()解析時驗證文檔的內容,激活各種選項,諸如實體替換、DTD屬性不一致等。演示使用xmlTextReaderPreservePattern()提取XML文檔中某一部分的子文檔。演示重用xmlReader對象來解析多個XML文檔。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章