目的
把json文本转成xml文本表示
KJSonToXml.h
#define BANK_ID L"id"
#define BANK_TEXT L"text"
#define BANK_CHILDREN L"children"
struct BankInfo
{
int nId;
CString strName;
std::vector<BankInfo*> vecBankInfo;
};
enum {
TypeError = 0,
TypeNull = 1,
TypeObject,
TypeBool,
TypeString,
TypeLong,
TypeFloat,
TypeArray,
};
class KJSonToXml
{
public:
KJSonToXml(void);
~KJSonToXml(void);
void OutPutXmlFromJson(const CString& strJsonFilePath);
private:
void _ParseJson(BankInfo* pBankinfo, BkJson::Handle& jsonHander);
void _WriteXmlInfo(BankInfo* pBankinfo, KTinyXml& tinyXml);
private:
BankInfo m_root;
};
KJSonToXml.cpp
#include "StdAfx.h"
#include "KJSonToXml.h"
KJSonToXml::KJSonToXml(void)
{
}
KJSonToXml::~KJSonToXml(void)
{
}
void KJSonToXml::OutPutXmlFromJson(const CString& strJsonFilePath)
{
BkJson::Document jsonDoc;
if (!jsonDoc.LoadFile(strJsonFilePath, CP_UTF8))
return;
m_root.nId = jsonDoc[BANK_ID];
m_root.strName = jsonDoc[BANK_TEXT];
_ParseJson(&m_root, jsonDoc);
KTinyXml tinyXml;
tinyXml.Open("root", TRUE);
_WriteXmlInfo(&m_root, tinyXml);
tinyXml.SaveFile(L"C:\\test.xml");
}
void KJSonToXml::_ParseJson(BankInfo* pBankinfo, BkJson::Handle& jsonHander)
{
if (NULL == pBankinfo)
return;
if (!jsonHander.HasKey(BANK_CHILDREN))
return;
BkJson::Handle& jsonTemp = jsonHander[BANK_CHILDREN];
if (TypeArray == jsonTemp.GetType())
{
int nCnt = jsonTemp.Count();
for (int i = 0; i < nCnt; i++)
{
BankInfo* pInfo = new BankInfo();
pInfo->nId = jsonTemp[i][BANK_ID];
pInfo->strName = jsonTemp[i][BANK_TEXT];
pBankinfo->vecBankInfo.push_back(pInfo);
_ParseJson(pInfo, jsonTemp[i]);
}
}
else
{
BankInfo* pInfo = new BankInfo();
pInfo->nId = jsonTemp[BANK_ID];
pInfo->strName = jsonTemp[BANK_TEXT];
pBankinfo->vecBankInfo.push_back(pInfo);
}
}
void KJSonToXml::_WriteXmlInfo(BankInfo* pBankinfo, KTinyXml& tinyXml)
{
if (NULL == pBankinfo)
return;
tinyXml.AddChild("bank", TRUE);
tinyXml.Write("id", pBankinfo->nId);
tinyXml.Write("name", pBankinfo->strName);
if (0 == pBankinfo->vecBankInfo.size())
return;
int nSize = (int)pBankinfo->vecBankInfo.size();
for (int i = 0; i < (int)nSize; i++)
{
BankInfo *pTempInfo = pBankinfo->vecBankInfo[i];
_WriteXmlInfo(pTempInfo, tinyXml);
tinyXml.ParentElement();
}
}