TinyXml读写

这两天抽空熟悉了一下快忘了的TinyXml,写了读写xml的两个函数

//解析根元素和组元素
bool parseElement(const TiXmlNode* pRoot)
{
    if (pRoot == NULL)
    {
        return false;
    }
    for (const TiXmlNode* pChild = pRoot->FirstChild(); pChild; pChild = pChild->NextSibling())
    {
        if ((!strcmp(pChild->Value(), "Environment")) || (!strcmp(pChild->Value(), "Objects")))
        {
            cout << pChild->Value() << endl;
            parseElement(pChild);
        }
        else if ((!strcmp(pChild->Value(), "Sky")) || (!strcmp(pChild->Value(), "Object")))
        {
            cout << pChild->Value() << endl;
            parseElement(pChild);

        }
        else if ((!strcmp(pChild->Value(), "Property")))
        {
            cout << pChild->Value() << endl;
            const TiXmlElement* pElement = (const TiXmlElement*)pChild;
            const TiXmlAttribute* pFirstAttr = pElement->FirstAttribute();
            cout << pFirstAttr->Name() << endl;
            cout << pFirstAttr->Value() << endl;
        }
    }

    return true;

}

 

//创建XML配置文件
bool createXmlFile(string& sXFileName)
{
    TiXmlDocument* pXmlDoc = new TiXmlDocument;
    if (pXmlDoc == NULL)
    {
        return false;
    }

    TiXmlElement* pRootElem = new TiXmlElement("SecondScene");
    if (pRootElem == NULL)
    {
        return false;
    }
    pXmlDoc->LinkEndChild(pRootElem);

    TiXmlElement* pEnvElem = new TiXmlElement("Environment");
    if (pEnvElem == NULL)
    {
        return false;
    }
    pRootElem->LinkEndChild(pEnvElem);

    TiXmlElement* pObjectsElem = new TiXmlElement("Objects");
    if (pObjectsElem == NULL)
    {
        return false;
    }
    pRootElem->LinkEndChild(pObjectsElem);

    TiXmlElement* pObjElem = new TiXmlElement("Object");
    if (pObjElem == NULL)
    {
        return false;
    }
    pObjectsElem->LinkEndChild(pObjElem);
    pObjElem->SetAttribute("Name", "cow.osg");

    pXmlDoc->SaveFile(sXFileName);

    return true;

 

TinyXml用起来还是比较简单的,这里要提一下的是tinyxml与stl一起使用,这样比较方便,省的读写一个文件还得c_str,为了使用stl除了将lib文件换为tinyxmld_STL.lib外还得在预处理器定义里面定义一下TIXML_USE_STL,这样就OK了。


posted @ 2010-03-27 20:38  du's utopia  阅读(938)  评论(0编辑  收藏  举报