一个json转xml的例子

来源:互联网 发布:springer电子数据库 编辑:程序博客网 时间:2024/05/22 03:03
xml的<>里面很多字符都显示为非法,所以就转了下。json用的是jsoncpp开源库

intCCMPUtility::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;
}
原创粉丝点击