Detailed parsing of XML WebService full instances)

Source: Internet
Author: User
First, we must understand what is WebService. in terms of concept, it may be complicated, but we can have a macro understanding that WebService is an external interface with functions that can be called by external customers (note: there are also functions that cannot be called by the customer ). If we are a server, we have written a WebService and then gave it to the customer (and we also gave them the call rules ), the customer can be in a relatively transparent State when obtaining information from the server. That is, customers do not understand (or need to) the process, and they only obtain data.

The data transmitted by WebService can only be serialized data, typically XML data. Here we only discuss the transmission of XML data.

With some preliminary understanding of XML WebService, we will discuss the specific WebService usage in the form of a specific WebService example, using specific examples to explain a concept is easier to understand than simply speaking.

Here, we will take a simple distributed courseware search system as an example. Use vs2003 as the compiling environment, C # As the language, and sqlservcer2000 as the database. (This example is from an online friend'sArticleI think it is very representative of the characteristics of WebService, so I made such a system as an example)

First, clarify what we want to do. We need an interface to the customer, that is, a site. We call it servicegathersite. It doesn't matter in what form, even it doesn't need a database, it only provides users with a query interface, which is truly a service and is not accessible to common users. Then, we also need several sites that provide services. We can call them resource sites. For simplicity, we suppose there are two resource sites, websitea, websiteb, they may not be made public, but exist to enrich the query data. Finally, we need to pay attention to the service that the resource station provides to servicegathersite. The two resource sites have two services, namely siteaservice and sitebservice. there is no relationship between the two services, and the internal methods provided are completely unrelated. They just need to tell servicegathersite how to use the methods. This means that the service only provides the query interface and how to process the returned data, services are not managed by themselves. They are all allocated by the site using the services.

After writing so much, I briefly introduced the concept of XML WebService and the structure of our example. In the next article, we will start to enterCode.

The previous article introduced some basic features of WebService and the structure of our example. This article will begin with the specific coding work.

This topic focuses on WebService. Therefore, our code here focuses on WebService, while other projects, such as servicegathersite and websitea, will only be briefly introduced.

It is not difficult to develop a WebService in vs2003. First, we create a WebService Project (file-> New-> Project-> C #-> Web Service ApplicationProgram)

After this project is created, we will see a file named service1.asmx, which is the standard file of WebService. It also has the UI concept, but we generally do not pay attention to it, we can view its CS code file. If you haven't done anything yet, you will see a commented-out helloworld webmethod, remove the annotation, and run it to get the simplest WebService running instance. Click "helloworld" to execute its method. Obviously, this function only means to understand the Web Service writing method at a macro level.

Next, we will begin to introduce the WebService method in detail. In the code file, if we want this function to become an externally callable interface function after writing a function, we must add a line of code [webmethod (description = "function description")] to the function. If your function does not have this Declaration, it cannot be referenced by users. For example:

[Webmethod (description = "simplest method")]
Public String helloworld ()
{
Return "Hello World ";
}

This function is an externally callable interface function, which is equivalent to an API for users. if a user calls the helloworld () method after referencing this service, he will get the return value "helloworld.

We can see whether we have found that WebService is not so mysterious. It is just an interface. For us, the focus is on writing interface functions. Below, I will give the interface functions required in our example.

[Webmethod (description = "querying to obtain required courseware information")]
Public xmldatadocument getsiteadata (string assignname)
{
Xmldatadocument XD = new xmldatadocument ();//
Dataset DS = new dataset ();
Cstoreproc CP = new cstoreproc ("searchassign ");
CP. addparin ("@ keywords", sqldbtype. varchar, 30, assignname );
CP. addparout ("@ res", sqldbtype. INT );
If (CP. selectproc () // if the execution is successful, the stored procedure
{
CP. mydata. enforceconstraints = false; // The format is not strictly checked.
If (INT) CP. getreturnvalue ("@ res") =-1)
{
String xml = "";
XD. loadxml (XML );
Return XD;
}
XD = new xmldatadocument (CP. mydata );
Xmlnode root1 = XD. documentelement;
Xmlnodelist roots = root1.selectnodes ("list ");
Foreach (xmlnode roota in roots) // Add the site name tag to all elements
{
Xmlelement link = XD. createelement ("sitename ");
Link. innertext = configurationsettings. receivettings ["sitename"]. tostring ();
Roota. appendchild (Link );
}
Return XD;
}
Else return NULL;
}

This is an interface function for obtaining resource site information. For most of the Code in it, I think it should be clear to some friends who have a certain Asp.net base. Here we only describe cstoreproc, which is a stored procedure class I encapsulated, the main function is to execute various types of stored procedures.

Careful friends may find that the return type of this function seems special. It is an XML document. As we have mentioned earlier, WebService can only transmit serialized data. xml obviously meets the conditions, but non-serialized data such as hash tables cannot be transmitted. XML is the most widely used, considering cross-platform applications, we only use XML data transmission as an example.

[Nextpage]

Next, let's briefly explain the getsiteadata (string assignname) function.

The function is simple. You only need to return the query results. The data format is xmldatadocument. When the query fails (no matching query results), we construct an XML file and return an empty record. Otherwise, we will generate an xmldatadocument for the queried dataset. Next, due to the needs of this project, I add a loop to add nodes and site names that are not in the dataset. After that, we have completed an XML data document in the expected format and returned it.

Now, the WebService method function is fully introduced (here is a Web service method, which will be introduced later). How can we call this task next. First, compile the WebService project. Assume that this service is for Resource Site A and we may call it servicea. run the asmx file separately and run the getsiteadata (string assignname) method. You will be prompted to enter the parameters. Enter the content you want to search for and click "OK" to return an XML data record, it is displayed on IE, which is the content you searched.

Here we will introduce servicea's work. In our project, it is a service provided by resource site A, meaning that all the data it queries will come from site, the addition of Site A resources in this project also has a special project implementation.

Now, let's go back to the topic. Here I will introduce vs's WebService call method. In fact, the call methods on other platforms are similar. First, we will introduce the Web reference method, which is very convenient for debugging. Right-click "Reference", click "add web reference", and enter your WebService address, for example, http: // localhost/aspxproject/webservicesolution/sitebservice/service1.asmx, you must ensure that the entered WebService exists. Then you can reference it. Note that the Web reference name will be used as the namespace of the WebService you added. For example, if you enter sitea, the Service instantiation will be like this: sitea. service1 servicea = new sitea. service1 (); (service1 is the service class name ).

After this step is completed, the service call seems to be so simple. We have implemented remote instantiation, and the subsequent remote calls are equally easy. The binding code of the Resource Collection site servicegathersite is given below (only the information of Site A is collected)

 // bind data 
Public void binddata ()
{< br> servicea = new sitea. service1 ();
dataset DS = new dataset ();
xmlnode xmlnode1;
xmldatadocument XD = new xmldatadocument ();
stringbuilder xmlstring1;
xmlnode1 = servicea. getsiteadata (strsearch);
If (xmlnode1 = NULL) // -- stored procedure execution failed
return;
xmlstring1 = new stringbuilder (xmlnode1.outerxml );
If (xmlstring1.tostring (). equals ("")
return;
XD. loadxml (xmlstring1.tostring ();
DS. readxml (New xmlnodereader (xd);
datagrid1.datasource = Ds. tables ["list"]. defaultview;
datagrid1.databind ();
}

This code segment provides a solution for converting XML into dataset. Although this is not necessary, we all know the role of dataset in Asp.net. For other users, please read it first (haha, the master will be exempted from it). In the next article, I will explain some of it and write three articles on the solution for calling multi-service distribution, it seems that some of my friends have read this, so I will continue to write it out of ugliness. If you have any comments, you may wish to raise them. In this case, it is inevitable that there will be some misunderstandings. I hope you will understand them :)

Next, let's briefly describe the binding function. First, instantiate servicea. This is not the same as the instantiation of general classes ...... Next, use xmlnode1 to accept the return value of the function. Next, construct the XML and convert it to dataset. This is a common method. If you are new friends, you 'd better write down this method.

The code for Asynchronously calling two services is provided.

// Bind data
Public void binddata ()
{
Iasyncresult AR1;
Iasyncresult AR2;
Servicea = new sitea. service1 ();
Serviceb = new siteb. service1 ();
Dataset DS = new dataset ();
Xmlnode xmlnode1, xmlnode2;
Xmldatadocument XD = new xmldatadocument ();
Stringbuilder xmlstring1, xmlstring2;
// -- Simple asynchronous call
AR1 = servicea. begingetsiteadata (strsearch, null, null );
AR2 = serviceb. begingetsiteadata (strsearch, null, null );
Xmlnode1 = servicea. endgetsiteadata (AR1 );
Xmlnode2 = serviceb. endgetsiteadata (AR2 );
//----------
If (xmlnode1 = NULL & xmlnode2 = NULL) // -- stored procedure execution failed
Return;
Xmlstring1 = new stringbuilder (xmlnode1.outerxml );
Xmlstring2 = new stringbuilder (xmlnode2.outerxml );
Xmlstring1 = makenewxmlstring (xmlstring1, xmlstring2); // generate a new XML
If (xmlstring1.tostring (). Equals (""))
Return;
XD. loadxml (xmlstring1.tostring ());
DS. readxml (New xmlnodereader (xd ));
Datagrid1.datasource = Ds. Tables ["list"]. defaultview;
Datagrid1.databind ();
}
// Generate new XML
Public stringbuilder makenewxmlstring (stringbuilder str1, stringbuilder str2)
{
Str1 = str1.replace ("","");
Str2 = str2.replace ("","");
Str1.append (str2.tostring ());
Return str1;
}

There are two points to note: XML structure and asynchronous calling implementation. Please understand them yourself.

The following describes how to reference WebService through DLL. I will only introduce the process.

First, enter the service address in IE, such as ttp: // www.xxx.com/service.asmx.

Then write and enter ttp: // www.xxx.com/service.asmx? WSDL

Open it and save it as XXX. WSDL

Run the vs command prompt to compile: WSDL/namespace: sitea servicea. WSDL.

Generate a proxy class with the namespace as sitea

Finally, CSC/out: servicea. dll/T: Library service1.cs. service1.cs is the proxy file.

Finally, you can reference the DLL.

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.