一个json转xml的例子

xml的<>里面很多字符都显示为非法,所以就转了下。json用的是jsoncpp开源库

int CCMPUtility::jsonToXmlString(Json::Value value,std::string &strXml)
{
if(0 == value.size()) return -1;
std::vector<std::string> vecKeys = value.getMemberNames();
for(std::vector<std::string>::iterator it = vecKeys.begin();it != vecKeys.end();it++)
{
std::string strKey = *it;
//const char *szNum = strKey.c_str();
std::string strKeyNoSpace;
//if(isdigit(*szNum))
strKeyNoSpace = "prefix_"+strKey;/*XML tag cannot begin with a number*/
//else
// strKeyNoSpace = strKey;
replaceString(strKeyNoSpace," ","_");/*XML tag cannot include space*/
replaceString(strKeyNoSpace,"^","");/*XML tag cannot include space*/
if(value[strKey.c_str()].isArray())
{
Json::Value array = value[strKey.c_str()];
std::string strArray="";
strXml += "<"+strKeyNoSpace+">\n";
for(Json::Value::iterator itV = array.begin();itV != array.end();itV++)
{
std::string str;
if((*itV).isString())
{
str = (*itV).asString();
}
else if((*itV).isInt())
{
int nItem = (*itV).asInt();
std::ostringstream stream;
stream<<nItem;
str = stream.str();
}
if(!str.empty())
strXml += "<li>"+str+"</li>\n";
}
strXml += "</"+strKeyNoSpace+">";
}
else if(value[strKey.c_str()].isObject())
{
Json::Value ItemValue = value[strKey.c_str()];
strXml += "<"+strKeyNoSpace+">";
jsonToXmlString(ItemValue,strXml);
strXml += "</"+strKeyNoSpace+">";
}
else if(value[strKey.c_str()].isString())
{
std::string strItem = value[strKey.c_str()].asString();
if(!strItem.empty())
strXml  += "<"+strKeyNoSpace+">"+strItem+"</"+strKeyNoSpace+">\n";
}
else if(value[strKey.c_str()].isInt())
{
std::ostringstream stream;
stream << value[strKey.c_str()].asInt();
std::string strItem = stream.str();
if(!strItem.empty())
strXml  += "<"+strKeyNoSpace+">"+strItem+"</"+strKeyNoSpace+">\n";
}

}
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值