c++TinyXmlを使用してXmlを読み書きする
最近、xmlを読み込むのに長いこと探していたので、TinyXmlを手に入れてxmlを読み書きしました.これは彼らの評価がいいので、研究しました.しかし、私は、簡単に勉強します.理解が浅い.
TinyXmlのダウンロード後、ファイルが多いです.実は多くは役に立たず、主に6つのファイル、2つのhヘッダファイル、4つのcppファイルです.
tinystr.cpp、tinystr.h、tinyxml.cpp、tinyxml.h、tinyxmlerror.cpp、tinyxmlparser.cpp
私は整理して、資源の中に置いて、みんなを歓迎してダウンロードします:http://download.csdn.net/detail/open520yin/4827542
注意:この6つのファイルは、あなたたちのプロジェクトにコピーできません.これは使えないようです.includeはちょっと問題があるようです.自分でファイルを作って、コードを入れることをお勧めします.私は最初から過去をコピーしていたので、どうしてもだめでした...急いで私のようにサボらないでください.初心者はサボってはいけません.ほほほ.
そして、コピーしたら、この4つのcppファイルの一番上に
次は私の例です.見てもいいです.注釈がはっきりしている.
TinyXmlのダウンロード後、ファイルが多いです.実は多くは役に立たず、主に6つのファイル、2つのhヘッダファイル、4つのcppファイルです.
tinystr.cpp、tinystr.h、tinyxml.cpp、tinyxml.h、tinyxmlerror.cpp、tinyxmlparser.cpp
私は整理して、資源の中に置いて、みんなを歓迎してダウンロードします:http://download.csdn.net/detail/open520yin/4827542
注意:この6つのファイルは、あなたたちのプロジェクトにコピーできません.これは使えないようです.includeはちょっと問題があるようです.自分でファイルを作って、コードを入れることをお勧めします.私は最初から過去をコピーしていたので、どうしてもだめでした...急いで私のようにサボらないでください.初心者はサボってはいけません.ほほほ.
そして、コピーしたら、この4つのcppファイルの一番上に
#include "stdafx.h"
私は4つも追加するかどうか分かりませんが、どうせ私はすべて追加しました.運行も正しいです.次は私の例です.見てもいいです.注釈がはっきりしている.
// ConsoleApplication11.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include "tinyxml.h"
#include "tinystr.h"
using namespace std;
//
class Person
{
public:
string m_sName;
string m_sNickName;
int m_nAge;
};
// xml
void SaveXml(Person* person, string file)
{
TiXmlDocument xmlDoc;
//
TiXmlNode* rootElement = xmlDoc.InsertEndChild(TiXmlElement("Person"));
//
rootElement
->InsertEndChild(TiXmlElement("Name"))
->InsertEndChild(TiXmlText(person->m_sName.c_str()));
//
rootElement
->InsertEndChild(TiXmlElement("NickName"))
->InsertEndChild(TiXmlText(person->m_sNickName.c_str()));
//
char buffer[256];
_itoa(person->m_nAge, buffer,10);
rootElement
->InsertEndChild(TiXmlElement("Age"))
->InsertEndChild(TiXmlText(buffer));
//
xmlDoc.SaveFile(file.c_str());
}
// xml
void LoadXml(string file, Person* person)
{
//
TiXmlDocument xmlDoc(file.c_str());
xmlDoc.LoadFile();
//
if(xmlDoc.ErrorId() > 0)
return;
// , Persons。
TiXmlElement* pRootElement = xmlDoc.RootElement();
//
if(!pRootElement)
return;
TiXmlElement* pNode = NULL;
// name
pNode = pRootElement->FirstChildElement("Name");
if(pNode)
{
person->m_sName = pNode->GetText();
}
// NickName
pNode = pRootElement->FirstChildElement("NickName");
if(pNode)
{
person->m_sNickName = pNode->GetText();
}
// Age
pNode = pRootElement->FirstChildElement("Age");
if(pNode)
{
person->m_nAge = atoi(pNode->GetText());
}
}
//
int _tmain(int argc, _TCHAR* argv[])
{
string file = "Person.xml";
Person Larry;
Larry.m_sName = "Larry";
Larry.m_sNickName = " ";
Larry.m_nAge = 30;
SaveXml(&Larry, file);
Person NewLarry;
// , NewLarry
LoadXml(file, &NewLarry);
printf("Name: %s\r
", NewLarry.m_sName.c_str());
printf("NickName: %s\r
", NewLarry.m_sNickName.c_str());
printf("Age: %d\r
", NewLarry.m_nAge);
return 0;
}