大家好,又见面了,我是你们的朋友全栈君。
1.tinyXMl生成XML文件
#include <stdio.h>
#include <string>
using namespace std;
#include "../tinyxml/tinyxml.h"
int test1()
{
TiXmlDocument xml_doc;
// 添加XML声明
xml_doc.LinkEndChild(new TiXmlDeclaration( "1.0", "GBK", "" ));
// 添加根元素
TiXmlElement * xml_root = new TiXmlElement("root");
xml_doc.LinkEndChild(xml_root);
// 在根元素下添加其他子元素
if(1)
{
// 添加host
TiXmlElement* xml_child = new TiXmlElement("host");
xml_root->LinkEndChild(xml_child );
// 添加文档内容
xml_child->LinkEndChild( new TiXmlText("AAA"));
// 设置属性
xml_child->SetAttribute("checked", "true");
xml_child->SetAttribute("station", 1001);
}
if(1)
{
// 嵌套子元素
TiXmlElement* xml_client = new TiXmlElement("client");
xml_root->LinkEndChild(xml_client );
TiXmlElement* xml_clientName = new TiXmlElement("name");
xml_clientName->LinkEndChild( new TiXmlText("xiaoming"));
xml_client->LinkEndChild(xml_clientName);
TiXmlElement* xml_clientId = new TiXmlElement("id");
xml_clientId->LinkEndChild( new TiXmlText("201801"));
xml_client->LinkEndChild(xml_clientId);
}
// 保存到文件
xml_doc.SaveFile("example.xml");
// 或者转成string
string text ;
text << xml_doc;
return 0;
}
int main()
{
test1();
return 0;
}
生成的文件如下:
<?xml version="1.0" encoding="GBK" ?>
<root>
<host checked="true" station="1001">AAA</host>
<client>
<name>xiaoming</name>
<id>200801</id>
</client>
</root>
示例2:
<?xml version="1.0" encoding="UTF-8" ?>
<Persons>
<Person Number="1">
<name>sunsusn</name>
<price>22.5</price>
</Person>
</Persons>
#include <iostream>
#include <string>
#include "xml/tinyxml.h"
#include "xml/tinystr.h"
using namespace std;
int main()
{
string fileName = "test.xml";
TiXmlDocument *doc = new TiXmlDocument(); //创建xml文档对象
TiXmlDeclaration *pDeclaration = new TiXmlDeclaration("1.0","UTF-8","");
doc->LinkEndChild(pDeclaration);
TiXmlElement *RootLv1 = new TiXmlElement("Numbers"); //创建一个根结点
doc->LinkEndChild(RootLv1); //链接到文档对象下
TiXmlElement *RootLv2 = new TiXmlElement("number"); //创建一个节点
RootLv1->LinkEndChild(RootLv2); //链接到节点RootLv1下
RootLv2->SetAttribute("Number", "1"); //设置节点RootLv2属性
TiXmlElement *Name = new TiXmlElement("name"); //创建节点
RootLv2->LinkEndChild(Name); //链接节点到RootLv2下
TiXmlElement *Price = new TiXmlElement("price"); //创建节点
RootLv2->LinkEndChild(Price); //链接节点到RootLv2下
TiXmlText *NameText = new TiXmlText("Robin"); //创建XmlText文本
Name->LinkEndChild(NameText); //链接到Name下
TiXmlText *PriceText = new TiXmlText("22.5"); //创建XmlText
Price->LinkEndChild(PriceText); //链接到Price下
doc->SaveFile("c:\\test.xml"); //保存到文件
return 0;
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/135237.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...