网上的文章乱七八糟的,还不如官方的一个例子:http://sourceforge.net/projects/tinyxml/files/?source=navbar
一个解析xml字符串的接口:
- /*循环获取某段xml中某个子标签的若干个子标签中的值*/
- bool GetPicUrls(const char* pContent,std::list<string>& pic_url_list)
- {
- TiXmlDocument doc( "demotest.xml" );
- doc.Parse( pContent );
- if ( doc.Error() )
- {
- printf( "Error in %s: %s\n",doc.Value(),doc.ErrorDesc() );
- return false;
- }
- doc.SaveFile();
- //TiXmlDocument doc( "demotest.xml" );
- bool loadOkay = doc.LoadFile();
- if ( !loadOkay )
- {
- printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n",doc.ErrorDesc() );
- return false;
- }
- TiXmlNode* node = 0;
- TiXmlNode* childNode = 0;
- TiXmlNode* childNodeUrl = 0;
- TiXmlElement* todoElement = 0;
- //TiXmlElement* itemElement = 0;
- node = doc.FirstChild( "AAAAA" );//母节点
- if (node)
- {
- node = node->FirstChild("BBBBB");
- if (node)
- {
- node = node->FirstChild("CCCCC");//找到要循环遍历的子节点的母节点
- }
- }
- if (node)
- {
- childNode = node->FirstChild("xxxx");//找到第一个xxxx节点
- while (childNode)
- {
- childNodeUrl = childNode->FirstChild("xx");
- string strUrl;
- todoElement = childNodeUrl->ToElement();//转化成标签处理
- strUrl = todoElement->GetText();//获取标签的值
- pic_url_list.push_back(strUrl);
- const TiXmlNode* prevIoUsNode = childNode;
- childNode = node->IterateChildren("xxxx",prevIoUsNode);//下一个xxxx节点
- }
- }
- return true;
- }
上面的代码中保存本地文档的步骤可注释掉。基本的思想是先将整个xml当做一个dom,然后寻找到需要的节点,然后将其转化成标签处理。当然在找到某个节点的位置后,还可以进行插入节点等操作。