背景解释。编程语言c++,实际项目上会用MFC,数据下载方式为gsoap,拉下来的数据类型为string,用tinyxml对拉下来的string类型进行解析,其中的中文字符都是乱码,用iconv来解码(from utf-8 to GBK)。
//main.cpp
1 #include "AppServiceSoap.nsmap" 2 #include "soapAppServiceSoapProxy.h" 3 #include "iconv.h" 4 #include "tinystr.h" 5 #include "tinyxml.h" 6 7 using namespace std; 8 9 #define OUTPUT_LEN 2048 10 #define FIELD_LEN 16 11 12 int conv_charset(const char *dest, const char *src, char *input, size_t ilen, char *output, size_t olen) 13 { 14 iconv_t conv = iconv_open(dest, src); 15 if (conv == (iconv_t)-1) 16 return -1; 17 memset(output, 0, olen); 18 19 if (iconv(conv, (const char **)&input, &ilen, &output, &olen)) 20 return -1; 21 iconv_close(conv); 22 return 0; 23 } 24 25 int main() 26 { 27 AppServiceSoapProxy webservice; 28 soap_init(webservice.soap); 29 soap_set_mode(webservice.soap, SOAP_C_UTFSTRING); 30 31 _WS1__SampleDataByBarCodeNoXML request = _WS1__SampleDataByBarCodeNoXML(); 32 string tmp = "18010354204"; 33 request.sSampleBarCodeNo = &tmp; 34 35 _WS1__SampleDataByBarCodeNoXMLResponse response = _WS1__SampleDataByBarCodeNoXMLResponse(); 36 37 char *endpoint = NULL; 38 39 int result = webservice.SampleDataByBarCodeNoXML(&request, response); 40 41 if (SOAP_OK == result) 42 { 43 //int element_counter = response.SampleDataByBarCodeNoXMLResult->__sizestring; 44 cout << *response.SampleDataByBarCodeNoXMLResult <<endl; 45 cout << "--------------------开始解码--------------------" << endl; 46 47 TiXmlDocument* myDocument = new TiXmlDocument(); 48 myDocument->Parse((*(response.SampleDataByBarCodeNoXMLResult)).c_str(), 0, TIXML_ENCODING_UTF8); 49 TiXmlElement* rootElement = myDocument->RootElement(); 50 TiXmlElement* studentsElement = rootElement->FirstChildElement(); 51 studentsElement = studentsElement->FirstChildElement(); 52 53 while (studentsElement) 54 { 55 cout << studentsElement->Value() << ":"; 56 57 if (studentsElement->GetText()) 58 { 59 int ilen = strlen(studentsElement->GetText()); 60 int olen = ilen * 2; 61 char *output = (char *)malloc(sizeof(char) * olen); 62 char* input = nullptr; //初始化char*类型 63 64 input = const_cast<char*>(studentsElement->GetText()); //const char*类型转char*类型 65 66 conv_charset("GBK", "UTF-8", input, ilen, output, olen); 67 cout << output << endl; 68 } 69 else 70 { 71 cout << "(此项无内容)" << endl; 72 } 73 74 studentsElement->utf8ByteTable; 75 76 //迭代下一个 77 studentsElement = studentsElement->NextSiblingElement(); 78 } 79 } 80 //结束了 81 soap_destroy(webservice.soap); 82 soap_end(webservice.soap); 83 soap_done(webservice.soap); 84 85 cout << "---------------------finish-----------------------" << endl; 86 cin.get(); 87 return 0; 88 }
项目的目录结构。
主要分成3部分。
1、gsoap。
先做soap,这个参考上一篇。
2、tinyxml。
这个比较简单。
3、iconv.h,iconv.lib
这个好难。我都是用别人编译好的。
参考:https://www.cnblogs.com/tangxin-blog/p/5608751.html。