tinyXML一款很优秀的操作C++类库,文件不大,但方法很丰富,和apache的Dom4j可以披靡啊!习惯了使用java类库的我看到这么丰富的c++类库,很高兴!它使用很简单,只需要拷贝几个文件到你的工程中,没有STL也可以编译运行。
/* * Main.cpp * * Created on: 2015-1-26 * Author: Administrator */ #includexml文件#include #include #include "tinystr.h" #include "tinyxml.h" using namespace std; int main() { const char* filepath = "phonebookdata.xml"; TiXmlDocument doc(filepath); bool loadOkay = doc.LoadFile(); // faile to load 'phonebookdata.xml'. if (!loadOkay) { printf("Could not load test file %s. Error='%s'. Exiting.\n", filepath, doc.ErrorDesc()); exit(1); } // get dom root of 'phonebookdata.xml', here root should be 'phonebook'. TiXmlElement* root = doc.RootElement(); // trace every items below root. for (TiXmlNode* item = root->FirstChild("item"); item; item = item->NextSibling("item")) { // read name. TiXmlNode* child = item->FirstChild(); const char* name = child->ToElement()->GetText(); if (name) { printf("name:%s\n", name); } else { printf("name:\n"); } // read address. child = item->IterateChildren(child); const char* addr = child->ToElement()->GetText(); if (addr) { printf("addr:%s\n", addr); } else { printf("addr:\n"); } // read telephone no. child = item->IterateChildren(child); const char* tel = child->ToElement()->GetText(); if (tel) { printf("tel:%s\n", tel); } else { printf("tel:\n"); } // read e-mail. child = item->IterateChildren(child); const char* email = child->ToElement()->GetText(); if (email) { printf("email:%s\n", email); } else { printf("email:\n"); } printf("\n"); } TiXmlElement* writeRoot = doc.RootElement(); TiXmlNode* newNode = new TiXmlElement("item"); const TiXmlNode* name4NewNode = new TiXmlElement("name"); newNode->InsertEndChild(*name4NewNode)->InsertEndChild(TiXmlText("pipi")); const TiXmlNode* addr4NewNode = new TiXmlElement("addr"); newNode->InsertEndChild(*addr4NewNode)->InsertEndChild( TiXmlText("Shaanxi Xianyang")); const TiXmlNode* tel4NewNode = new TiXmlElement("tel"); newNode->InsertEndChild(*tel4NewNode)->InsertEndChild( TiXmlText("02937310627")); const TiXmlNode* email4NewNode = new TiXmlElement("email"); newNode->InsertEndChild(*email4NewNode)->InsertEndChild( TiXmlText("pipi@home.com")); writeRoot->InsertEndChild(*newNode); doc.SaveFile(); return 0; }
miaomaio Shaanxi Xi'an 13759911917 miaomiao@home.com gougou Liaoning Shenyang 15840330481 gougou@home.com pipi Shaanxi Xianyang 02937310627 pipi@home.com pipi Shaanxi Xianyang 02937310627 pipi@home.com
收藏的用户(0) X
正在加载信息~
推荐阅读
最新回复 (0)
站点信息
- 文章2302
- 用户1336
- 访客10968998
每日一句
Qingming Festival invites us to honor ancestors with quiet reflection and respect.
清明节邀请我们以静思与敬意祭奠祖先。
清明节邀请我们以静思与敬意祭奠祖先。
新会员