C++ XML JSON格式轉換

  • 2019 年 11 月 6 日
  • 筆記

數據格式在編程裡面很常見,不同的系統都會有自己的標準。因為給有各的定義,每次做第三方開發系統對接的時候數據格式標準都是頭疼的事情。

在開發過程中比較常見的比如有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 ;  }

這次我們使用tinyxml2 和nlohmann json 做轉換,需要將兩者的頭文件和源程式碼文件下載,並在編譯中include。

nolhmann json 需要C++ 11 的支援,gcc版本需要在4.7以上。

可以使用下面命令編譯:

g++ -std=c++11 xmljson.cpp tinyxml2.cpp -I./

./a.out  {"appid":"appid-value111111","mch_id":"mch_id-value22222","nonce_str":"nonce_str-value3333333","sign":"sign-value5555555555","transaction_id":"transaction_id-value44444444"}  <xml>      <appid>appid-value111111</appid>      <mch_id>mch_id-value22222</mch_id>      <nonce_str>nonce_str-value3333333</nonce_str>      <sign>sign-value5555555555</sign>      <transaction_id>transaction_id-value44444444</transaction_id>  </xml>

Tags: