C + + Request Web service and XML parsing

Source: Internet
Author: User
Tags gettext wsdl

1. Open Source Library for C + + parsing xml

The parsing of XML in the project uses an open-source third-party library,TinyXML; the model of this parsing library is generated in the XML file and then in memory DOM model so that we can easily traverse the XML Tree.

The DOM model, the Document object model, divides the entire document into elements such as books, chapters, sections, paragraphs, and so on, and uses a tree structure to represent the order relationships between these elements and the nested include relationships. Take a look at the corresponding relationship between the main class in TinyXML and the XML document, which is the main classes in TinyXML class diagram, which reflects the static relationship between the various classes.

Tixmlbaseis the base class for all classes,Tixmlnode,Tixmlattributetwo classes are inherited from aTixmlbaseclass, amongTixmlnodeclass refers to all the<...>...<.../>contains the content, whileXMLthe nodes in this section are divided into the following aspects, which are declarations, stares, nodes, and the text between nodes, soTixmlnodeon the basis of these several classes are derivedtixmlcomment,tixmldeclaration,tixmldocument,tixmlelement,Tixmltext,Tixmlunknown, respectively, to indicate that the details areXMLwhich part of the. Tixmlattributeclass differs fromTixmlnode, which refers to the contents of the face in the angle brackets, like<...***=...>, among***is an attribute that is used here as aXMLThe documentation is described in detail:

1.<?xml version= "1.0"  encoding= "UTF-8"?>  2.<phonebook>  3.     <!--one item behalfs one contacted person.-->  4.     <item>  5.        <name> Miaomaio</name>  6.    <addr>shaanxi xi ' an</addr>   7.    <tel>13759911917</tel>  8.    < email>[email protected]</email>  9.    </item>   10.    <item>  11.        <name >gougou</name>  12.    <addr>Liaoning Shenyang</addr>   13.    <tel>15840330481</tel>  14.     <email>[email protected]</email>  15.    </item>  16.      <!--more contacted persons.-->  </phonebook> 

L like Tixmldeclaration refers to <?xml version= "1.0" encoding= "UTF-8"?

L like Tixmlcomment refers to <!--one item Behalfs one contacted Person.-->, <!--more contacted Persons.-->

L like Tixmldocument refers to the entire XML document,

L like Tixmlelement refers to <phonebook>, <item>, <name>, <addr> and so on these nodes,

L like Tixmltext refers to ' Gougou ', ' 15840330481 ' which are sandwiched between <item> and </item>, <name> and </name>, <addr> and </addr> text between the texts,

L like Tixmlattribute refers to <?xml version= "1.0" encoding= "UTF-8"?> node in version, encoding,

L Besides that is tixmlunknown.

1) Read the XML file
!xml file read, the impersonation call interface returns char * string Filebuf *pbuf;ifstream filestr;long Size;char *buffer;filestr.open (xml_example_file_ NAME, ios::binary);p buf = Filestr.rdbuf (); size = Pbuf->pubseekoff (0,ios::end,ios::in);p buf->pubseekpos (0, iOS: : in), buffer = new Char[size];p buf->sgetn (buffer, size), Filestr.close (),//! get correlation value from XML string Strcreationtime; String strjobid;string strjobtype;string strjobname;string strjobleader; Tixmldocument *xmldocument = new Tixmldocument () xmldocument->parse (buffer, 0, tixml_default_encoding); Tixmlelement *rootelement = Xmldocument->rootelement (); Tixmlelement *fileheaderelement = Rootelement->firstchildelement (); Tixmlelement *filebodyelement = Fileheaderelement->nextsiblingelement (); for (tixmlelement *nodeElement = Fileheaderelement->firstchildelement (); Nodeelement; Nodeelement = Nodeelement->nextsiblingelement ()) {string strelementkey = Nodeelement->value (); if ( Strelementkey.compare (xml_parse_creation_time) = = 0) {strcreationtime = Nodeelement-> GetText ();}} for (Tixmlelement *nodeelement = Filebodyelement->firstchildelement (); nodeelement; nodeelement = nodeElement-> Nextsiblingelement ()) {string strelementkey = Nodeelement->value (); if (Strelementkey.compare (xml_parse_job_id) = = 0) {strjobid = Nodeelement->gettext ();} if (Strelementkey.compare (xml_parse_job_type) = = 0) {Strjobtype = Nodeelement->gettext ();} if (Strelementkey.compare (xml_parse_job_name) = = 0) {strjobname = Nodeelement->gettext ();} if (Strelementkey.compare (xml_parse_job_leader) = = 0) {Strjobleader = Nodeelement->gettext ();}}
2) Create and generate XML files

Take an example of the following XML file:

<?xml version= "1.0" encoding= "gb2312" ><InterFaceFile>     <FileHeader>          <MessageType> proxymiddlewarejobsearch</messagetype>          <Originator>WetLand</Originator>  < recipient>platform</recipient>          <creationtime>2014-9-18 10:25:20</creationtime>     </FileHeader>     <FileBody>          <UserName>...</UserName>          <userroleid>13 </UserRoleID>           <JobType></JobType>      </FileBody></InterFaceFile>

//! Build XML string Tixmldocument *pdoc = new Tixmldocument; Tixmldeclaration *pdeclaration = new Tixmldeclaration ("1.0", "gb2312", "" ");pD Oc->linkendchild (pdeclaration); Tixmlelement *peleroot = new Tixmlelement ("Interfacefile");pD Oc->linkendchild (peleroot); Tixmlelement *pelefileheader = new Tixmlelement ("Fileheader"); Tixmlelement *pelefilebody = new Tixmlelement ("Filebody");p eleroot->linkendchild (pelefileheader);p eleroot-> Linkendchild (Pelefilebody); Tixmlelement *pelemessagetype = new Tixmlelement ("MessageType"); Tixmlelement *peleoriginator = new Tixmlelement ("originator"); Tixmlelement *pelerecipient = new Tixmlelement ("Recipient"); Tixmlelement *pelecreationtime = new Tixmlelement ("CreationTime");p Elefileheader->linkendchild (PEleMessageType) ;p elefileheader->linkendchild (peleoriginator);p elefileheader->linkendchild (pelerecipient); Pelefileheader->linkendchild (Pelecreationtime); Tixmltext *pelemessagetypetext = new Tixmltext ("Proxymiddlewarejobsearch"); Tixmltext *peleoriginatOrtext = new Tixmltext ("wetland"); Tixmltext *pelerecipienttext = new Tixmltext ("Platform"); Tixmltext *pelecreationtimetext = new Tixmltext ("2014-9-18 10:25:20");p Elemessagetype->linkendchild ( Pelemessagetypetext);p eleoriginator->linkendchild (peleoriginatortext);p Elerecipient->linkendchild ( Pelerecipienttext);p elecreationtime->linkendchild (pelecreationtimetext);//! Tixmlelement *peleusername = new Tixmlelement ("UserName"); Tixmlelement *peleuserroleid = new Tixmlelement ("Userroleid"); Tixmlelement *pelejobtype = new Tixmlelement ("JobType");p elefilebody->linkendchild (peleusername);p elefilebody- >linkendchild (Peleuserroleid);p elefilebody->linkendchild (Pelejobtype); Tixmltext *peleusernametext = new Tixmltext ("..."); Tixmltext *peleuserroleidtext = new Tixmltext ("13"); Tixmltext *pelejobtypetext = new Tixmltext ("");p Eleusername->linkendchild (peleusernametext);p eleuserroleid-> Linkendchild (Peleuserroleidtext);p elejobtype->linkendchild (pelejobtypetext);pD oc->savefile ("E:/houqd.xml "); 

3) generating an XML string

Generating an XML string simply requires replacing the pdoc->savefile ("E:/houqd.xml") above with the following example:

! Generate string String Tixmlprinter printer;pdoc->accept (&printer); string strrequest (printer. CSTR ());
2. C + + Tune Soap's Open Source Library

We use gSOAP as an open-source Web service implementation framework that can be downloaded from the Web to open source code implementations. :http://gsoap2.sourceforge.net/ Generic downloaded gSOAP toolkit already includes the build web ServiceClient required two tools (executable files): Wsdl2h.exe and Soapcpp2.exe,windows development packages generally under GSOAP/BIN/WIN32, WSDL2H does not support SSL by default. It is impossible to access the HTTPS website, pretend to support many other features such as SSL, you need to configure the gSOAP toolkit to generate new Wsdl2h.exe and soapcpp2.h. Here, I'm using the native file.

Related references:http://blog.csdn.net/zhaiwenjuan/article/details/6590941

1) gSOAP generate local agent

1> generating the corresponding header file based on WSDL

Gets the WSDL file for the Web service from the Web services provider , typically a URL, such as:http://www.somewebservice.com/Service?Wsdl, of course, can also be a Wsdl form of XML files.

Using the Wsdl2h.exe of gSOAP, a header file is generated from the WSDL-C + + syntax structure.

For example: Wsdl2h.exe-s-o Service.h http://www.somewebservice.com/Service?Wsdl

When this step is finished, you will get a header file such as: Service.h

The purpose of this step is to implement a data map of the WSDL file to the. h file.

2> generating related proxy files based on generated header files

Use gSOAP 's precompiled soapcpp2.exetogenerate stub files based on the header files obtained in the previous step soapStub.h And the client code framework:

such as:soapcpp2.h-i-x-c-L Service.h

This step will get several . Nsmap,. h , and . cpp files. The purpose of this step: generate the corresponding underlying communication code.

2) gSOAP call WebService interface

Add the files that were generated in the previous steps to project and include the header file for the response, using the following invocation methods:

String Strrequest (printer. CSTR ());//!web Service Tune interface string strwebserviceaddr = "http://172.16.10.209:8080/HDHT_J2EE/services/ PROXYMIDDLEWAREJOB?WSDL "; Proxymiddlewarejobhttpbindingproxy *proxy = new Proxymiddlewarejobhttpbindingproxy (); _ns1__ Proxymiddlewarejobsearch Inputparam;_ns1__proxymiddlewarejobsearchresponse outputparam;inputparam.in0 = const_cast <char *> (Strrequest.c_str ());p Roxy->proxymiddlewarejobsearch (Null,strwebserviceaddr.c_str (), & Inputparam, Outputparam); string strresult = Outputparam.out;
3. Problems in the process of the tune-up 1) The issue of the transfer of parameters

Here, when using the Web service call interface, based on the idea (the way the PHP Web service calls), it is assumed that the C + + invocation of the transfer of the parameters as a direct pass, For example, when the Proxymiddlewarejobsearch interface is called above, it receives an XML-formatted string and returns an XML-formatted string, so when it is first used, it is invoked as follows:

Proxy->proxymiddlewarejobsearch (NULL, Strwebserviceaddr.c_str (), Strrequest, strresult), string form used, the result has been an error, It means that the const char * cannot be converted to a _ns1__proxymiddlewarejobsearch * form, and it should be used in later applications such as the following:

_ns1__proxymiddlewarejobsearch Inputparam; //! Represents input

_ns1__proxymiddlewarejobsearchresponse Outputparam; ! Represents the output

Inputparam.in0 = Const_cast<char *> (strrequest.c_str ()); ! Enter the first number of parameters,

Assuming that the interface requires a second parameter, the call is: Inputparam.in1 = ...

string strresult = Outputparam.out; //! The return of the result after the call.

2) Chinese garbled problem

Workaround: In Java to build the Web service side, before returning the string, base64 encryption, and then C + + as the client of the Web service after the method is called, the string is decrypted first Base64, so there is no garbled problem.

C + + Implementation Base64 code references link:

Http://www.cnblogs.com/phinecos/archive/2008/10/10/1308272.html

C + + Request Web service and XML parsing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.