C++生成xml(使用tinyxml)


  解析及庫安裝方法在上一篇文章里。

  我是按照這個網站上的xml樣式寫的例程。

  由於原xml屬性過多,我只取了3個標示並且每個標示取4個屬性,以便簡化流程。

代碼如下:

#include <iostream>
#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;
}

貌似有內存泄露,不過為了清晰的顯示結構,不管那么多了。

最后生成如下文件:

<?xml version="1.0" ?>
<CSTALOG CD="3" Attribute="4">
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
    <CD>
        <TITLE>Greatest Hits</TITLE>
        <ARTIST>Dolly Parton</ARTIST>
        <PRICE>9.90</PRICE>
        <YEAR>1982</YEAR>
    </CD>
</CSTALOG>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM