zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    leetcode 912. 排序数组
    leetcode 633. 平方数之和
    leetcode 1512. 好数对的数目
    leetcode 1822. 数组元素积的符号
    leetcode 145. 二叉树的后序遍历
    leetcode 11. 盛最多水的容器
    leetcode 28 实现strStr()
    leetcode 27. 移除元素
    leetcode 26. 删除有序数组中的重复项
    产品化思维之公式系统
  • 原文地址:https://www.cnblogs.com/tiandsp/p/2852762.html
Copyright © 2011-2022 走看看