【C++】【TinyXml】xml文件的读写功能使用——写xml文件

来源:互联网 发布:java火车票订票系统 编辑:程序博客网 时间:2024/05/23 19:11

TinyXml工具是常用比较简单的C++中xml读写的工具

需要加载


#include "TinyXml\tinyxml.h"

在TinyXML中,根据XML的各种元素来定义了一些类:

TiXmlBase:整个TinyXML模型的基类。

TiXmlAttribute:对应于XML中的元素的属性。

TiXmlNode:对应于DOM结构中的节点。

TiXmlComment:对应于XML中的注释

TiXmlDeclaration:对应于XML中的申明部分,即<?versiong="1.0" ?>。

TiXmlDocument:对应于XML的整个文档。

TiXmlElement:对应于XML的元素。

TiXmlText:对应于XML的文字部分

TiXmlUnknown:对应于XML的未知部分。 

TiXmlHandler:定义了针对XML的一些操作。


读取xml文件方法

TiXmlDocument doc;                              if (!doc.LoadFile(fullPath.c_str(), TIXML_ENCODING_UTF8)){cout << "can not parse xml" << endl;}

其中TIXML_ENCODING_UTF8是为了防止在中文名称时出现乱码

 

写XML文件方法:

文档类TiXmlDocument

TiXmlDocument doc;string outputFilePath = “E:\\text.xml”;TiXmlElement *converterElement = new TiXmlElement("Converter");doc.LinkEndChild(converterElement);doc.SaveFile(outputFilePath.c_str());

元素结点类TiXmlElement

添加节点方法LinkEndChild(TiXmlNode* node)

设置节点属性方法SetAttribute( const char * cname, const char * cvalue )

TiXmlDocument doc;string outputFilePath = “E:\\text.xml”;TiXmlElement *converterElement = new TiXmlElement("Converter");doc.LinkEndChild(converterElement); TiXmlElement *configureElement = new TiXmlElement("Configure");converterElement->LinkEndChild(configureElement); TiXmlElement *generalElement = new TiXmlElement("Options");configureElement->LinkEndChild(generalElement);generalElement->SetAttribute("Name", "General");<br><br>doc.SaveFile(outputFilePath.c_str());

效果如下
<Converter>    <Configure>        <Options Name="General">    </Configure></Converter>

内容类TiXmlText
TiXmlElement *OptionElement = new TiXmlElement("Option");OptionElement->SetAttribute("Name", “Value”);TiXmlText *NameContent = new TiXmlText(“text”);OptionElement->LinkEndChild(NameContent); return OptionElement;

效果如下
<Option Name="Value">text</Option>

0 0
原创粉丝点击