體驗TinyXML讀寫XML文件數(shù)據(jù)
前一陣子做一個客服回復(fù)玩家問題工具,要用到讀寫XML文件的數(shù)據(jù),同事推薦用TinyXML,于是,開始了我與TinyXML的親密之旅。
先簡單說說配置:首先下載TinyXML庫的文件,然后在 TinyXML 的目錄里面找到tinystr.h, tinyxml.h,tinystr.cpp,tinyxml.cpp, tinyxmlerror.cpp,tinyxmlparser.cpp六個文件加入到自己的項目中去,在相應(yīng)的工程文件中加入兩個頭文件 #include "tinyxml.h" ,#include "tinystr.h",在 tinystr.cpp,tinyxml.cpp, tinyxmlerror.cpp, tinyxmlparser.cpp四個文件的第一行加入頭文件 #include "stdafx.h",然后即可使用TinyXML編程。
要讀取的xml 數(shù)據(jù)如下:
- <?xml version="1.0" encoding="gb2312" standalone="yes" ?>
- <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <prop>
- <id>100</id>
- <title>test 1</title>
- </prop>
- <prop>
- <id>200</id>
- <title>test 2</title>
- </prop>
- </root>
注意要將 encoding設(shè)為gb2312格式,我一開始設(shè)置的是utf-8,結(jié)果遇到在程序里
寫入中文沒問題, 但在讀出該中文時卻有異常,把后面的 </ 符號也當(dāng)作值讀出來
了,后來和一同事討論后才知道是編碼問題。
- string filefullPath = 要讀取xml文件的絕對路徑
- //創(chuàng)建文件對象
- TiXmlDocument * myDocument = new TiXmlDocument(filefullPath.c_str());
- //加載文件數(shù)據(jù)
- myDocument->LoadFile();
- //獲取根節(jié)點
- TiXmlElement *RootElement = myDocument->RootElement();
以下是簡單的讀取操作:
- //第一個子節(jié)點
- TiXmlElement *CurrentPerson = RootElement->FirstChildElement();
- //遍歷獲取指定節(jié)點數(shù)據(jù)
- while(CurrentPerson)
- {
- //子節(jié)點第一個屬性 id
- TiXmlElement *IdElement = CurrentPerson->FirstChildElement();
- //第一個屬性的值
- int nodeID = atoi(IdElement->FirstChild()->Value());
- //子節(jié)點第二個屬性 title
- TiXmlElement *TitleElement = IdElement->NextSiblingElement();
- //第二個屬性的值
- CString nodeTitle = TitleElement->FirstChild()->Value();
- .....................
- 如果還有后續(xù)節(jié)點,依次讀取
- .....................
- 維護讀出的數(shù)據(jù)
- .....................
- //指向下一節(jié)點
- CurrentPersonCurrentPerson = CurrentPerson->NextSiblingElement();
- }
以下是增加xml記錄的操作,例如要增加 id 為 300,title 為 test3 的記錄:
- //創(chuàng)建節(jié)點對象
- TiXmlElement *PersonElement = new TiXmlElement("prop");
- //鏈接到根節(jié)點
- RootElement ->LinkEndChild(PersonElement);
- //創(chuàng)建節(jié)點對象的屬性節(jié)點
- TiXmlElement *IdElement = new TiXmlElement("id");
- TiXmlElement *TitleElement =new TiXmlElement("title");
- //將屬性節(jié)點鏈接到子節(jié)點
- PersonElement->LinkEndChild(IdElement);
- PersonElement->LinkEndChild(TitleElement);
- //創(chuàng)建屬性對應(yīng)數(shù)值對象
- TiXmlText *idContent = new TiXmlText("300");
- TiXmlText *titleContent = new TiXmlText("test3");
- //將數(shù)值對象關(guān)聯(lián)到屬性節(jié)點
- IdElement->LinkEndChild(idContent);
- TitleElement->LinkEndChild(titleContent);
- //保存到文件
- myDocument->SaveFile(m_filefullPath.c_str());
以下是刪除記錄操作,例如要刪除id為300 的記錄:
- //獲取當(dāng)前要刪除的節(jié)點
- TiXmlElement * childElement = 根據(jù)id從自己讀取時緩存的數(shù)據(jù)中獲得
- //從根節(jié)點移除子節(jié)點
- RootElement->RemoveChild(childElement);
- //保存文件
- myDocument->SaveFile(m_filefullPath.c_str());
學(xué)習(xí)TinyXML主要是要理解其節(jié)點的層次關(guān)系,通曉其筋脈,則運用自如。
原文鏈接:http://www.cnblogs.com/skydesign/archive/2011/11/08/2240528.html
【編輯推薦】