C++经常使用函数 XML JSON格式转换php
数据格式在编程里面很常见,不一样的系统都会有本身的标准。由于给有各的定义,每次作第三方开发系统对接的时候数据格式标准都是头疼的事情。html
在开发过程当中比较常见的好比有Json、XML、Key-Value等。这里咱们就先看看Json和XML。二者的转换有不少开源的代码可使用,并且也很完善,能够参考xml2json 、xsltjson 。ios
XML在Json出现前应用很普遍,灵活性好,应用语言也没有限制,发展了这么长时间后xml标准已经很臃肿。这里能够查看XML的标准 XML标准。在C++里面解析和操做XML的库也有很多,tinyxml 就是个不错的选择,体积少、简单、高效的开源库,如今已经发布了TinyXml-2.c++
Json出来后当即被不少高级语言做为了标准推荐使用,若是想了解Json的定义请点击这里:JSON定义git
接下来,我想作个简单的函数来转换。github
<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格式的自由转换。shell
#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以上。json
可使用下面命令编译:app
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>
C++经常使用函数 XML JSON格式转换 https://www.cppentry.com/benc...