C++常用函数之XML JSON格式转换问题

2020-03-01 10:01:05于丽

数据格式在编程里面很常见,不同的系统都会有自己的标准。因为给有各的定义,每次做第三方开发系统对接的时候数据格式标准都是头疼的事情。

在开发过程中比较常见的比如有Json、XML、Key-Value等。这里我们就先看看Json和XML。两者的转换有很多开源的代码可以使用,而且也很完善,可以参考xml2json、xsltjson。

XML在Json出现前应用很广泛,灵活性好,应用语言也没有限制,发展了这么长时间后xml标准已经很臃肿。这里可以查看XML的标准XML标准。在C++里面解析和操作XML的库也有不少,tinyxml 就是个不错的选择,体积少、简单、高效的开源库,现在已经发布了TinyXml-2.

Json出来后立即被很多高级语言作为了标准推荐使用,如果想了解Json的定义请点击这里:JSON定义

XML2Json & Json2XML

接下来,我想做个简单的函数来转换。

<xml>
  <appid>appid-value111111</appid>
  <mch_id>mch_id-value22222</mch_id>
  <nonce_str>nonce_str-value3333333</nonce_str>
  <transaction_id>transaction_id-value44444444</transaction_id>
  <sign>sign-value5555555555</sign>
</xml>

上面的报文是在三方支付里面常见的报文,这次我们来实现对这段报文的Json格式的自由转换。

#include <string>
#include <iostream>
#include "tinyxml2.h"
#include "nlohmann/json.hpp"

using json = nlohmann::json;
using namespace tinyxml2;
using namespace std;

string xml2json(string &src)
{
  XMLDocument doc;
  doc.Parse( src.c_str() );
  
  json root;
  XMLElement* rootElement = doc.RootElement();
  XMLElement* child = rootElement->FirstChildElement();
  while(child) {
    const char* title = child->Name() ;
    const char* value = child->GetText();
    child = child->NextSiblingElement();
    root[title]=value ;
  }
  return root.dump() ;
}

string json2xml(string& src)
{
  XMLDocument xmlDoc;
  XMLNode * pRoot = xmlDoc.NewElement("xml");
  xmlDoc.InsertFirstChild(pRoot);
  auto j3 = json::parse(src.c_str());
  for (json::iterator it = j3.begin(); it != j3.end(); ++it) {
    string key = it.key();
    string value = it.value() ;
    XMLElement * pElement = xmlDoc.NewElement(key.c_str()) ;
    pElement->SetText(value.c_str()) ;
    pRoot->InsertEndChild(pElement);
  }
  XMLPrinter printer;
  pRoot->Accept( &printer );
  return printer.CStr();
}

int main()
{
  string src = "<xml>
          <appid>appid-value111111</appid>
          <mch_id>mch_id-value22222</mch_id>
          <nonce_str>nonce_str-value3333333</nonce_str>
          <transaction_id>transaction_id-value44444444</transaction_id>
          <sign>sign-value5555555555</sign>
        </xml>" ;
  string json = xml2json(src) ;
  string xml = json2xml(json) ;

  cout << json ;
  cout << endl ;
  cout << xml ;
}