其實在網(wǎng)上很容易能找到使用libxml2來對xml文檔進行創(chuàng)建、解析、修改等。我著這里主要是就自己學習的libxml2修改xml文檔的節(jié)點進行一個簡單的總結(jié),方便自己以后回顧。 下面給出我寫的一個例子: /*********************************************************
其實在網(wǎng)上很容易能找到使用libxml2來對xml文檔進行創(chuàng)建、解析、修改等。我著這里主要是就自己學習的libxml2修改xml文檔的節(jié)點進行一個簡單的總結(jié),方便自己以后回顧。下面給出我寫的一個例子:
/********************************************************************** Copyright, 2011, **** Tech. Co., Ltd. All Rights Reserved ----------------------------------------------------------------------- Project Code : wlan File name : modify_node.cpp Author : Sky_qing Description : 使用libxml2修改xml文檔的節(jié)點 Function List: ----------------------------------------------------------------------- History: Date Author Modification 2011-12-27 Sky_qing created file **********************************************************************/ #include#include "libxml/parser.h" #include "libxml/tree.h" int main(int argc, char* argv[]) { xmlDocPtr doc; //定義解析文檔指針 xmlNodePtr curNode; //定義節(jié)點指針(在各個節(jié)點之間移動) char* szDocName = argv[1]; //保存xml文檔名,該文檔名在運行程序到時候輸入。 //例如:編譯格式為g++ modify_node.cpp -o modify_node -I /usr/local/include/libxml2/ -L /usr/local/lib -lxml2,生成可執(zhí)行文件modify_node,運行時:./modify_node log4crc(此處log4crc為要修改的xml文檔) printf("........start........\n"); doc = xmlReadFile(szDocName, "utf-8", XML_PARSE_RECOVER); //解析文檔 if (NULL == doc) { fprintf(stderr, "Document not parsed successfully.\n"); return -1; } curNode = xmlDocGetRootElement(doc); //確定文檔根元素 if (NULL == curNode) { fprintf(stderr, "Empty Document.\n"); xmlFreeDoc(doc); //釋放文件 return -1; } if (xmlStrcmp(curNode->name, (const xmlChar*)"log4c")) //確認根元素是否為“l(fā)og4c” { fprintf(stderr, "Document of wrong type. root node != log4c"); xmlFreeDoc(doc); return -1; } curNode = curNode->xmlChildrenNode; xmlNodePtr propNode = curNode; while (NULL != curNode) //遍歷所有節(jié)點 { //獲取名稱為category的節(jié)點 if (!xmlStrcmp(curNode->name, (const xmlChar*)"category")) { //查找?guī)в袑傩詎ame的節(jié)點 if (xmlHasProp(curNode, BAD_CAST "name")) { propNode = curNode; } //查找屬性name為WLAN_Console的節(jié)點 xmlAttrPtr attrPtr = propNode->properties; while (NULL != attrPtr) //遍歷所有名稱為category的節(jié)點 { if (!xmlStrcmp(attrPtr->name, (const xmlChar*)"name")) //找到有name屬性到節(jié)點 { //查找屬性為name的值的節(jié)點 xmlChar* szPropity = xmlGetProp(propNode, (const xmlChar*)"name"); if (!xmlStrcmp((const xmlChar*)szPropity, (const xmlChar*)"WLAN_Console")) { xmlAttrPtr setAttrPtr = propNode->properties; while (NULL != setAttrPtr) { //設(shè)置屬性priority的值 xmlSetProp(propNode, (const xmlChar*)"priority", (const xmlChar*)"debug"); setAttrPtr = setAttrPtr->next; } } } attrPtr = attrPtr->next; } } curNode = curNode->next; } //保存文檔到原文檔中 xmlSaveFile("log4crc", doc); printf("...........OK............\n"); return 0; }
編譯和運行格式在代碼中有。
參考文章:
http://blog.sina.com.cn/s/blog_669e9f6a0100sbql.html
http://wenku.baidu.com/view/02d0fdea172ded630b1cb61c.html
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com