TinyXml的使用

使用TinyXml创建xml文件时,必须动态创建TiXmlElement对象,因为TiXmlDocument的析构函数会自动遍历根节点下的所有子节点(TiXmlElement)并将其删除,如果TiXmlElement是栈上的对象,由于超出生命周期会自动释放,而TiXmlDocument的析构函数又会再一次将其释放,从而造成错误。

读取并解析xml文件时则没有这个问题。

 

// MyTinyXmlTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <tinyxml.h>
#include <windows.h>
//#include <vld.h>
using namespace std;

 #ifndef IN
 #define IN
 #endif
 
 #ifndef OUT
 #define OUT
 #endif

void CreateXmlFile(const char *pSavePath)
{
    TiXmlDocument doc;

    //创建根节点
    //必须使用New方式创建TiXmlElement对象,因为TiXmlDocument的析构函数会将所有子节点删除
     TiXmlElement *pNode = new TiXmlElement("Node");
     doc.LinkEndChild(pNode);
 
      TiXmlElement *pChild = new TiXmlElement("Child_1");
      pChild->SetAttribute("id", "1");
      pChild->SetAttribute("info", "test");
      pNode->LinkEndChild(pChild);
  
      TiXmlText *pChildText = new TiXmlText("it's the text of Child_1");
      pChild->LinkEndChild(pChildText);

    doc.SaveFile(pSavePath);
}

void ParseXml(TiXmlElement *pNode)
{
    if (!pNode)
        return ;

    TiXmlAttribute *pAttrElement = NULL;

    while(pNode)
    {
        //节点的名字
        cout<<"<"<<pNode->Value();

        //获取当前节点的属性值
        pAttrElement = pNode->FirstAttribute();
        while(pAttrElement)
        {
            cout<<" "<<pAttrElement->Name()<<"="<<pAttrElement->Value()<<" ";
            //获取当前节点的下一个属性值
            pAttrElement = pAttrElement->Next();
        }
        cout<<">"<<endl;
        
        //如果节点有数据,输出节点的数据
        if (pNode->GetText())
            cout<<pNode->GetText()<<endl;

        ParseXml(pNode->FirstChildElement());

        cout<<"</"<<pNode->Value()<<">"<<endl; 

        //获取兄弟节点,即同一级节点
        pNode = pNode->NextSiblingElement();

    }
}

void ReadXmlTest(const char *pFilePath)
{
    TiXmlDocument doc;
    if ( !doc.LoadFile(pFilePath) )
    {
        cout<<"cannot load xmm file : "<<pFilePath<<endl;
        return ;
    }

    //获取根节点
    TiXmlElement *pNode = doc.RootElement();

    //从根节点开始递归,一直到最后一个叶子节点
    ParseXml(pNode);
}

char *GetAppFath(OUT char *pFilePath, IN int nPathLen)
{
    ::GetModuleFileName(NULL, pFilePath, nPathLen);
    char* pTemp = strrchr(pFilePath, '\\');
    *(pTemp+1) = 0x0;

    return pFilePath;
}

int _tmain(int argc, _TCHAR* argv[])
{
    char szFilePath[MAX_PATH];
    GetAppFath(szFilePath, MAX_PATH);
    strcat(szFilePath, "\\MyTest.xml");
    
    CreateXmlFile(szFilePath);
    ReadXmlTest(szFilePath);

    system("pause");

    return 0;
}

 

 

 

posted @ 2012-06-01 15:53  terry.zhou  阅读(215)  评论(0)    收藏  举报