天天看點

C++使用下載下傳TinyXML

先下載下傳TinyXML,百度一下就行,下載下傳下來解壓,裡面有2個頭檔案和4個cpp檔案,一起加到工程裡面,如圖所示

http://up.2cto.com/2013/0830/20130830105328361.jpg

xmlTest.cpp是包含主函數的檔案,下面直接上代碼,很簡單,不管怎麼樣,總算是實作了,雖然題目要求不使用外加類庫實作,過段時間等題解出來我再上來更新不加外庫實作的方法。

<School name="軟體學院">    
    <Class name = "C++">    
        <Student name="tinyxml" number="123">    
            <email>[email protected]</email>    
            <address>中國</address>             
        </Student>    
        <Student name="jsoncpp" number="456">    
            <email>[email protected].com</email>    
            <address>美國</address>             
        </Student>    
    </Class>    
</School>


//以上是要讀取xml檔案,下面的是xmlTest.cpp。 


#include <iostream>  
#include "tinystr.h"  
#include "tinyxml.h"  
#include <string>  
using namespace std;  


void readSchoolXml() {  
    using namespace std;  
    const char * xmlFile = "school.xml";  
    TiXmlDocument doc;                                
    if (doc.LoadFile(xmlFile)) {  
        doc.Print();  
    } else {  
        cout << "can not parse school.xml" << endl;  
        return;  
    }  
    TiXmlElement* rootElement = doc.RootElement();  //School元素    
    TiXmlElement* classElement = rootElement->FirstChildElement();  // Class元素  
    TiXmlElement* studentElement = classElement->FirstChildElement();  //Students    
    for (; studentElement != NULL; studentElement = studentElement->NextSiblingElement() ) {  
        TiXmlAttribute* attributeOfStudent = studentElement->FirstAttribute();  //獲得student的name屬性    
        for (;attributeOfStudent != NULL; attributeOfStudent = attributeOfStudent->Next() ) {  
            cout << attributeOfStudent->Name() << " : " << attributeOfStudent->Value() << std::endl;         
        }                                   

        TiXmlElement* studentContactElement = studentElement->FirstChildElement();//獲得student的第一個聯系方式   
        for (; studentContactElement != NULL; studentContactElement = studentContactElement->NextSiblingElement() ) {  
            string contactType = studentContactElement->Value();  
            string contactValue = studentContactElement->GetText();  
            cout << contactType  << " : " << contactValue << std::endl;             
        }     
    }   
int main(){  
    readSchoolXml();  
    system("pause");  
    return ;  
}

           

運作結果如下

http://up.2cto.com/2013/0830/20130830105337743.jpg

原文連結:

http://www.2cto.com/kf/201308/239962.html

c++

繼續閱讀