C++產生xml(使用tinyxml)

來源:互聯網
上載者:User

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

  我是按照這個網站上的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>

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.