加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用tinyxml生成xml

发布时间:2020-12-16 06:17:28 所属栏目:百科 来源:网络整理
导读:我想使用tinyxml生成如下xml: ?xml version="1.0" encoding="GB2312" standalone="yes" ? Man ver="3.0" Hobby Day="forever"编程/Hobby /Man ---------------------------------------------------------------------------- 代码如下: // Tinyxml_Test.cp

我想使用tinyxml生成如下xml:

<?xml version="1.0" encoding="GB2312" standalone="yes" ?>
<Man ver="3.0">
<Hobby Day="forever">编程</Hobby>
</Man>

----------------------------------------------------------------------------

代码如下:

// Tinyxml_Test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string>
using std::string;

// tinyxml
#include "./lib/tinyxml/tinyxml.h"
#pragma comment(lib,"./lib/tinyxml/tinyxml.lib")
#pragma comment(linker,"/NODEFAULTLIB:libc.lib")   // 禁用默认库libc.lib,不然编译会出错

int _tmain(int argc,_TCHAR* argv[])
{
    TiXmlDocument doc;  // 代表整个XML

    // 生成 <?xml version="1.0" encoding="GB2312" standalone="yes" ?>
    // 这个相当于XML的头了
    TiXmlDeclaration* pxmlDecl = new TiXmlDeclaration("1.0","GB2312","yes");
    if (pxmlDecl == NULL)
    {
        return 0;
    }
    doc.LinkEndChild(pxmlDecl);

    // 生成XML根节点Man
    TiXmlElement* pXmlRootElement = new TiXmlElement("Man");
    if (pXmlRootElement != NULL)
    {
        pXmlRootElement->SetAttribute("ver","3.0");    // 根节点属性
        doc.LinkEndChild(pXmlRootElement);              // 根节点放入XML文档
    }

    // 根节点的第一个子节点
    TiXmlElement *pXmlElementChild = new TiXmlElement("Hobby");
    if (pXmlElementChild != NULL && pXmlRootElement != NULL)
    {
         pXmlRootElement->LinkEndChild(pXmlElementChild); 
    }
     

    // 设置子节点文本和属性
    TiXmlText *pXmlCmdText = new TiXmlText("编程");
    if (pXmlCmdText != NULL && pXmlElementChild != NULL)
    {
        pXmlElementChild->LinkEndChild(pXmlCmdText);
        pXmlElementChild->SetAttribute("Day","forever");
    }
   
    // 打印整个XML
    TiXmlPrinter printer;
    doc.Accept(&printer);
    printf("生成的xml:nn%s",printer.CStr());

    // 输出子节点属性
    if (pXmlElementChild != NULL)
    {
        const char *pDayValue= pXmlElementChild->Attribute("Day");
        printf("nDay=%s n",pDayValue);
        printf("子节点内容:%s",pXmlElementChild->GetText());
    }

    getchar();
	return 0;
}

---------------------------------------------------------------------

效果截图:

--------------------------------

例子工程下载:

Tinyxml_Test.rar

http://download.csdn.net/detail/friendan/8802169

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读