首先准备好tinyxml库中的六个文件(tinystr.cpp tinyxml.cpp tinyxmlerror.cpp tinyxmlparser.cpp tingystr.h tinyxml.h),这个百度一下就有了,因为不能上传附件,所以只能自己百度了,有需要可以给我留个言
要得到config.xml文件,创建在工程调试的目录中
config.xml文件如下:
<?xml version="1.0" encoding="gb2312" ?>
<matrixs>
<matrix id="111">矩阵</matrix>
<matrix id="222">矩阵</matrix>
<matrix id="333">矩阵</matrix>
</matrixs>
1、将这六个文件添加到所要用的工程中
2、编写代码
#include "tinystr.h"
#include "tinyxml.h"
#include <iostream>
#include <string>
#include "windows.h"
#define MAX_PATH 260
using namespace std;
int main()
{
//获取调试Debug文件夹下的目录地址
string sFilefullPath;
char xmlpath[MAX_PATH]={0};
char lpszFilePath[MAX_PATH] = {0};
char lpszDriver[_MAX_DRIVE], lpszDir[MAX_PATH], lpszFileName[_MAX_FNAME], lpszExt[_MAX_EXT];
int nLen = GetModuleFileName(NULL, lpszFilePath, MAX_PATH);
if(nLen != 0){
_splitpath(lpszFilePath, lpszDriver, lpszDir, lpszFileName, lpszExt);
memset(lpszFilePath, 0, sizeof(lpszFilePath));
strcat(lpszFilePath, lpszDriver);
strcat(lpszFilePath, lpszDir);
}
nLen = strlen(lpszFilePath);
if(nLen >1)
{
if('\\' != lpszFilePath[nLen-1])
{
strcat(lpszFilePath,"\\");
}
strcat(xmlpath,lpszFilePath);
strcat(xmlpath, "config.xml");
sFilefullPath=xmlpath;
}
//这时得到config.xml的路径为sFilefullPath
//新建xml文件
TiXmlDocument doc;
TiXmlDeclaration *dec=new TiXmlDeclaration("1.0","gb2312","");
TiXmlElement *matrixs=new TiXmlElement("matrixs");
doc.LinkEndChild(dec);
doc.LinkEndChild(matrixs);
TiXmlElement *matrix1 = new TiXmlElement("matrix");
matrixs->LinkEndChild(matrix1);
string strName1="矩阵";
TiXmlText *pStrName1=new TiXmlText(strName1.c_str());
matrix1->LinkEndChild(pStrName1);
matrix1->SetAttribute("id",111);
TiXmlElement *matrix2 = new TiXmlElement("matrix");
matrixs->LinkEndChild(matrix2);
string strName2="矩阵";
TiXmlText *pStrName2=new TiXmlText(strName2.c_str());
matrix2->LinkEndChild(pStrName2);
matrix2->SetAttribute("id",222);
TiXmlElement *matrix3 = new TiXmlElement("matrix");
matrixs->LinkEndChild(matrix3);
string strName3="矩阵";
TiXmlText *pStrName3=new TiXmlText(strName3.c_str());
matrix3->LinkEndChild(pStrName3);
matrix3->SetAttribute("id",333);
doc.SaveFile(sFilefullPath.c_str());
//读取 在控制台中输出属性
TiXmlDocument *myDocument = new TiXmlDocument(sFilefullPath.c_str());
myDocument->LoadFile();
TiXmlNode *RootElement = myDocument->RootElement();
TiXmlNode *root=myDocument->FirstChild("matrixs");
TiXmlElement *child;
for (child = root->FirstChildElement("matrix");child != 0;child = child->NextSiblingElement("matrix"))
{
string typeAttribute = child ->Attribute("id");
cout<<typeAttribute<<endl;
}
return 0;
}