TinyXML2读取和创建XML文件
发布时间:2020-12-16 09:14:59 所属栏目:百科 来源:网络整理
导读:TinyXML2是simple、small、efficient C++ XML文件解析库!方便易于使用,是对TinyXML的升级改写!源码见本人上传到CSDN的TinyXML2.rar资源:http://download.csdn.net/detail/k346k346/8500915,或者到官网下载:https://github.com/leethomason/tinyxml2。
TinyXML2是simple、small、efficient C++ XML文件解析库!方便易于使用,是对TinyXML的升级改写!源码见本人上传到CSDN的TinyXML2.rar资源:http://download.csdn.net/detail/k346k346/8500915,或者到官网下载:https://github.com/leethomason/tinyxml2。 使用方法:将tinyxml2.cpp和tinyxml2.h拷贝至项目目录,使用时包含#include "tinyxml2.h"和using namespace tinyxml2; 1.创建XML文件。注意:xml文件必须先创建,可由fopen()进行创建,再交由XMLDocument进行写入操作。
int createTinyXML2(string xmlPath) { FILE* fp=NULL; fp=fopen(xmlPath.c_str(),"w+");//创建空xml文件 fclose(fp);
XMLDocument doc; doc.LoadFile(xmlPath);//载入xml文件 XMLDeclaration* declaration=doc.NewDeclaration();//添加xml文件头申明 doc.InsertFirstChild(declaration);
XMLElement *Root = doc.NewElement("Root"); doc.InsertEndChild(Root);
//insert Head XMLElement* Head=doc.NewElement("Head"); Root->InsertEndChild(Head);
//insert Create_Time time_t rawtime;//time_t为long型 time(&rawtime);//获取从1970.1.1起的秒数 struct tm *temp = localtime(&rawtime); char time_str[32]; sprintf(time_str, "%04d-%02d-%02d %02d:%02d:%02d", temp->tm_year + 1900, temp->tm_mon + 1, temp->tm_mday, temp->tm_hour, temp->tm_mintm_sec); XMLElement* Create_Time = doc.NewElement("Create_Time"); Create_Time->InsertFirstChild(doc.NewText(time_str));
Head->InsertEndChild(Create_Time);
//insert Algorithm XMLElement* Algorithm = doc.NewElement("Algorithm"); Algorithm->InsertFirstChild(doc.NewText("MD5")); Algorithm->SetAttribute("ID",1); Head->InsertEndChild(Algorithm);
//insert cipher_Num XMLElement* Cipher_Num = doc.NewElement("Cipher_Num"); Cipher_Num->InsertFirstChild(doc.NewText("500")); Cipher_Num->SetAttribute("ID",2); Head->InsertEndChild(Cipher_Num);
int targetNum=3; while (targetNum) {
//insert Target Root->InsertEndChild(doc.NewElement("Target")); XMLElement* Target = Root->LastChildElement("Target"); //insert HashValue to Target Node XMLElement* HashValue = doc.NewElement("HashValue"); HashValue->InsertFirstChild(doc.NewText("5555")); Target->InsertEndChild(HashValue);
//insert Salt to Target Node XMLElement* Salt = doc.NewElement("Salt"); Salt->InsertFirstChild(doc.NewText("555")); Target->InsertEndChild(Salt);
targetNum--;
}
int result=doc.SaveFile(xmlPath.c_str()); return result; } 结果截图: 2.读取XML文件 int readTinyXML2(string xmlPath){XMLDocument doc; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |