C++:借助tinyxml2读取XML文件
// XMLT01.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include "tinyxml2.h"
using namespace std;
using namespace TinyXml2;
void ReadTest01XML()
{
XMLDocument doc;
doc.LoadFile("Test01.xml");
const char * content = doc.FirstChildElement("test")->GetText();
printf("%s\n",content);
}
void Printfln(const char * content, const char * name = "",const int n = 0, const char * notEqual1 = "", const char * notEqual2 = NULL)
{
for(int i = 0; i < n; i++)
{
printf(" ");
}
if(content != notEqual1 && content != notEqual2)
{
printf("%s: %s\n",name,content);
}
else
{
printf("%s: \n",name);
}
}
void ReadXML(const XMLElement *root)
{
if(NULL == root)
{
return;
}
static int flag = 0;
const char * rootName = NULL;
const char * rootContent = NULL;
const XMLAttribute * rootAttribute = NULL;
const char * rootAttributeName = NULL;
const char * rootAttributeValue = NULL;
rootName = root->Name();
rootContent = root->GetText();
rootAttribute = root->FirstAttribute();
if(NULL != rootAttribute)
{
rootAttributeName = rootAttribute->Name();
rootAttributeValue = rootAttribute->Value();
}
Printfln(rootContent,rootName,flag);
Printfln(rootAttributeValue,rootAttributeName,flag);
const XMLElement *child = root->FirstChildElement();
if(NULL != child)
{
flag++;
ReadXML(child);
}
const XMLElement * nextSibling = root->NextSiblingElement();
if(NULL != nextSibling)
{
ReadXML(nextSibling);
}
else
{
flag--;
return;
}
}
void ReadTest02XML()
{
XMLDocument doc;
doc.LoadFile("Test02.xml");
const XMLElement *root = doc.RootElement();
ReadXML(root);
system("pause");
}
int _tmain(int argc, _TCHAR* argv[])
{
ReadTest01XML();
ReadTest02XML();
return 0;
}