TinyXML使用

TinyXML使用

/*
TinyXML 官网
http://sourceforge.net/projects/tinyxml/

在TinyXML中,根据XML的各种元素来定义了一些类:
TiXmlBase:整个TinyXML模型的基类。
TiXmlAttribute:对应于XML中的元素的属性。
TiXmlNode:对应于DOM结构中的节点。
TiXmlComment:对应于XML中的注释
TiXmlDeclaration:对应于XML中的申明部分,如:<?xml version="1.0" encoding="UTF-8"?>
TiXmlDocument:对应于XML的整个文档。
TiXmlElement:对应于XML的元素。
TiXmlText:对应于XML的文字部分
TiXmlUnknown:对应于XML的未知部分。
TiXmlHandler:定义了针对XML的一些操作。

关键宏:TIXML_USE_STL
我是直接在tinyxml.h 中直接 #define TIXML_USE_STL
    
//xml文档

<?xml version="1.0" standalone="no" ?>
<!-- Our to do list data -->
<ToDo>
    <!-- Do I need a secure PDA? -->
    <Item priority="1" distance="close">菜单1
        <bold>Toy store!</bold>
    </Item>
    <Item priority="2" distance="none">菜单2</Item>
    <Item priority="2" distance="far &amp; back">Look for Evil Dinosaurs!</Item>
</ToDo>
*/


    
#include <stdio.h>
using  namespace std;
#include "tinyxml.h"

int main()
{
     int nVale ;
     int nRet ;
     string strValue;

    TiXmlDocument doc( "demotest.xml" );
     bool loadOkay = doc.LoadFile();

     if ( !loadOkay )
    {
        printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc() );
        exit( 1 );
    }

    TiXmlNode* node = 0;
    TiXmlElement* rootElement = 0;
    TiXmlElement* itemElement = 0;
    TiXmlElement* childElement = 0;

    rootElement = doc.RootElement();
    assert( rootElement );

    cout << rootElement->Value() << endl;

    itemElement = rootElement->FirstChildElement();    
        
    cout << itemElement->Value() << endl;

    cout << itemElement->FirstAttribute()->Value() << endl;

    nRet = itemElement->QueryIntAttribute("priority",&nVale);
     if (nRet==0) {
        cout << nVale << endl;
    }

    nRet = itemElement->QueryStringAttribute("distance",&strValue);
     if (nRet==0) {
        cout << strValue << endl;
    }

    strValue = itemElement->GetText();
    cout << strValue << endl;

    childElement = itemElement->FirstChildElement();
     if (childElement!=NULL)
    {
        strValue = childElement->Value();
        cout << strValue << endl;

        strValue = childElement->GetText();
        cout << strValue << endl;
    }
    
    itemElement = itemElement->NextSiblingElement();
    assert(itemElement);
    strValue = itemElement->GetText();
    cout << strValue << endl;
        
     return 0;
}
    

你可能感兴趣的:(TinyXML使用)