c++使用tinyxml创建xml文件

#include 
#include "tinyxml.h"
using namespace std;
#pragma comment(lib,"tinyxml.lib")

const char* AttributeName[4]={"TITLE","ARTIST","PRICE","YEAR"};
const char* Attribute[4][3]={{"Empire Burlesque","Hide your heart","Greatest Hits"},
                             {"Bob Dylan","Bonnie Tyler","Dolly Parton"},
                             {"10.90","9.90","9.90"},
                             {"1985","1988","1982"}};

int main()
{
    const char* xmlFile = "lianxi.xml";
    TiXmlDocument doc;      
    TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", ""); 
    doc.LinkEndChild(decl);

    TiXmlElement* firstLevel=new TiXmlElement("CSTALOG");
    firstLevel->SetAttribute("CD","3");
    firstLevel->SetAttribute("Attribute","4");
    
    for (int i=0;i<3;i++)
    {
        TiXmlElement* secondLevel=new TiXmlElement("CD");

        for (int j=0;j<4;j++)
        {
            TiXmlElement* thirdLevel=new TiXmlElement(AttributeName[j]);
            thirdLevel->LinkEndChild(new TiXmlText(Attribute[j][i]));
            secondLevel->LinkEndChild(thirdLevel);
        }

        firstLevel->LinkEndChild(secondLevel);
    }            
    doc.LinkEndChild(firstLevel);

    doc.SaveFile(xmlFile); 
    return 0;
}
复制代码
貌似有内存泄露,不过为了清晰的显示结构,不管那么多了。

最后生成如下文件:

复制代码


    
        Empire Burlesque
        Bob Dylan
        10.90
        1985
    
    
        Hide your heart
        Bonnie Tyler
        9.90
        1988
    
    
        Greatest Hits
        Dolly Parton
        9.90
        1982
    

TinyXML库的下载地址(http://download.csdn.net/detail/u013230291/9920039)

你可能感兴趣的:(c++编程基础)