c++使用調用xml文件

1. 首先下載這tinyxml官方文件庫。

http://download.csdn.net/download/llhhyy1989/4722355

 

2. 將其中文件放在目錄下。建立test.xml文件

<Server>

    <item> 

     <entrust_price>100.00</entrust_price> 

     <entrust_amount>1.0</entrust_amount> 

     <operator>10000</operator> 

     <entrust_direction>1</entrust_direction> 

    </item> 

    <item> 

     <entrust_price>101.00</entrust_price> 

     <entrust_amount>2.0</entrust_amount> 

     <operator>10001</operator> 

     <entrust_direction>2</entrust_direction> 

    </item> 

    <!--more contacted persons.--> 

</Server>

 

 

3.建立main.cpp文件

#include"tinyxml.h"

#include"tinystr.h"

#include<iostream>

#include<string>

#include<stdio.h>

#include<stdlib.h>

using namespacestd;

 

 

int main()

{

  /*way1. const char* filepath ="test.xml"; 

  TiXmlDocument doc(filepath); 

  bool loadOkay = doc.LoadFile(); 

  if (!loadOkay) {     

    cout<<"Could not load testfile."<<endl;

    exit( 1 ); 

    return 0;

  } */

  /*way2*/

  string xml_data ="<Server><item><entrust_price>100.00</entrust_price><entrust_amount>1.0</entrust_amount><operator>10000</operator><entrust_direction>1</entrust_direction></item><item><entrust_price>101.00</entrust_price><entrust_amount>2.0</entrust_amount><operator>10001</operator><entrust_direction>2</entrust_direction></item></Server>";

 

  TiXmlDocument *doc = new TiXmlDocument();

  doc->Parse(xml_data.c_str(),0,TIXML_ENCODING_UNKNOWN);

 

  TiXmlElement* root =doc->RootElement(); 

 

 

  for( TiXmlNode*  item = root->FirstChild( "item");  item; item = item->NextSibling( "item" ) ) { 

 

    TiXmlNode* child =item->FirstChild(); 

    const char* entrust_price =child->ToElement()->GetText(); 

    if (entrust_price) { 

      cout<<"entrust_price:"<<entrust_price<<endl;

    } else { 

     cout<<"entrust_price:"<<endl;

    } 

 

 

    child =item->IterateChildren(child); 

    const char* entrust_amount =child->ToElement()->GetText(); 

    if (entrust_amount) { 

      cout<<"entrust_amount:"<<entrust_amount<<endl;

    } else { 

     cout<<"entrust_amount:"<<endl; 

    }

 

    child =item->IterateChildren(child); 

    const char* operator_no =child->ToElement()->GetText(); 

    if (operator_no) { 

     cout<<"operator_no:"<<operator_no<<endl;

    } else { 

     cout<<"operator_no:"<<endl;

    } 

 

   

    child =item->IterateChildren(child); 

    const char* entrust_direction =child->ToElement()->GetText(); 

    if(entrust_direction) { 

       cout<<"entrust_direction:"<<entrust_direction<<endl;

    } else { 

       cout<<"entrust_direction:"<<endl;

    }

    cout<<endl;

  }

  delete doc;

}

 

 

其中方法一:主要是讀取本地配置文件,需要的時候指針指向的改爲對象引用

其中方法二:主要是針對XML報文,進行數據的傳輸。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章