How To Get Xsd From Web Service
A reader of my blog sent me an e-mail asking the following question:
"I have an XSD that I am required to utilise to export my company'due south data. How tin I use that XSD and return data to them in a web method? I should be able to render a data set with the data formatted the way the XSD defines but I have no idea how to practise that. Whatsoever ideas would salve me a ton of time and grief!"
Turns out this is a actually good question, and I remember ane a lot of developers struggle with primarily because the majority of developers are scared of XSD schemas. Hopefully I can modify that. An XML Schema is really simple and it is your friend.
What is an XSD or Xml Schema Definition?
An XML Schema describes the structure of an XML document.
That's information technology, see, information technology isn't that hard later on all!
As a programmer call back of an XSD the same style y'all would when creating business concern rules to validate objects before storing them into a database. Some items in objects cannot be nil, some can. Some demand to take their data formatted (email address for example) and others demand to not exceed certain lengths, etc.
When dealing with an XML document, we need to use the aforementioned type of rules and this is where the XSD comes in. Once we have an XSD to describe an XML certificate nosotros can guarantee any XML information we receive conforms to these rules.
Ok, enough intro, let's get coding.
The Schema
In the case of the reader's question, an XSD schema already existed. To salvage time, I've taken so general thought of the schema I was sent and slimmed it downward for simplicity sakes. The schema represents an XML document that will contain job listings. Hither is a view of the schema from the schema explorer in Visual Studio as well as the schema itself (again slimmed down).
<xsd:schema
xmlns:xsd="http://world wide web.w3.org/2001/XMLSchema"
targetNamespace="http://keithelder.cyberspace/Jobs"
xmlns:xs="http://keithelder.net/Jobs"><xsd:complexType proper noun="JobListing">
<xsd:sequence>
<xsd:element maxOccurs="unbounded" minOccurs="1" proper name="job" type="xs:Job" />
</xsd:sequence>
</xsd:complexType><xsd:complexType name="Chore">
<xsd:sequence>
<xsd:element maxOccurs="one" minOccurs="1" proper name="Title" type="xsd:cord"></xsd:element>
<xsd:chemical element maxOccurs="1" minOccurs="1" name="Description" type="xsd:string"></xsd:element>
<xsd:chemical element maxOccurs="1" minOccurs="1" name="Location" type="xs:Accost"></xsd:element>
<xsd:chemical element minOccurs="0" maxOccurs="1" name="PostingDate" type="xsd:date"></xsd:chemical element>
<xsd:element minOccurs="0" maxOccurs="one" name="CloseDate" type="xsd:engagement"></xsd:element>
<xsd:chemical element minOccurs="0" maxOccurs="1" proper noun="Benefits" blazon="xsd:cord"></xsd:chemical element>
<xsd:element maxOccurs="1" minOccurs="1" name="Salary" type="xsd:cord"></xsd:element>
<xsd:element maxOccurs="1" minOccurs="0" proper noun="JobType" type="xs:JobType"></xsd:element>
<xsd:chemical element minOccurs="0" maxOccurs="1" name="Function" type="xs:JobFunction"></xsd:element>
<xsd:element minOccurs="0" maxOccurs="ane" name="Category" type="xs:JobCategory"></xsd:element>
</xsd:sequence>
</xsd:complexType><xsd:simpleType name="JobType">
<xsd:brake base="xsd:string">
<xsd:enumeration value="full-time"></xsd:enumeration>
<xsd:enumeration value="part-fourth dimension"></xsd:enumeration>
<xsd:enumeration value="contractor"></xsd:enumeration>
</xsd:restriction>
</xsd:simpleType><xsd:complexType proper noun="Address">
<xsd:sequence>
<xsd:chemical element minOccurs="0" maxOccurs="one" name="Street" type="xsd:string"></xsd:element>
<xsd:element minOccurs="0" maxOccurs="1" proper noun="City" blazon="xsd:string"> </xsd:chemical element>
<xsd:element minOccurs="0" maxOccurs="one" name="Land" type="xsd:string"></xsd:element>
</xsd:sequence>
</xsd:complexType><xsd:simpleType name="JobCategory">
<xsd:restriction base of operations="xsd:cord">
<xsd:enumeration value="Automotive"/>
<xsd:enumeration value="Banking"/>
<xsd:enumeration value="Construction"/>
<xsd:enumeration value="Internet"/>
<xsd:enumeration value="Retail"/>
<xsd:enumeration value="Services"/>
</xsd:restriction>
</xsd:simpleType><xsd:simpleType name="JobFunction">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Chief Peanut Butter Spreader"/>
<xsd:enumeration value="I ran the whole transport"/>
<xsd:enumeration value="Other"/>
</xsd:brake>
</xsd:simpleType>
</xsd:schema>
One time we have a schema defined similar this we can generate code to be used for a service. We take a tool at our disposal that is available within the Visual Studio Command Prompt called XSD.exe. This executable does a lot of things simply 1 thing it can exercise is generate code from an XML Schema Definition.
When generating from the XSD file I was sent there was a problem with information technology. Here is the walk through of that story and so you can follow along.
When I commencement tried this on the reader'south original XSD I got an fault:
Alarm: cannot generate classes because no superlative-level elements with complex type were found.
What does this hateful? Well, await at the screen shot of the XML Schema Explorer in a higher place. Practice you see the <> green icons? Well those represent an XML Chemical element. An element is a fancy name for an XML tag similar: <Cows>Bramar</Cows>
Allow me roll this up and take another screen shot and then you can get-go to run into the problem (i accept to hit my magic number of 12 screen shots anyway :) ).
Encounter the problem? There isn't an element in this schema (no green <> thingy). What this ways is nosotros accept a schema which just lists complex types of elements and enumerations. There isn't whatsoever "xml" in this schema. The fix is elementary though. Add an chemical element to the schema.
<xsd:element name="JobListing" type="xs:Chore" />
Now nosotros accept a green thingy icon which means this XSD contains at least one element. Basically think of the JobListing element as the root chemical element.
Now that we accept an chemical element we can generate a C# grade file from this XSD:
The code generated is about 350 lines so I'm not going to include it in the commodity. There are some dainty things happening for u.s. when the C# classes are generated using xsd.exe. For starters the enumerations in the XSD are turned into C# enumerations. The classes are marked serializable and they have the appropriate XML attributes on the properties to serialize these objects into XML. This is a good affair since it ways nosotros didn't have to create it. Lawmaking generation is your friend. At present that nosotros take C# objects we can serialize these to XML hands.
The Service
The commencement matter we need to exercise is create the WCF service. For this example I chose to create a WCF Service Awarding in Visual Studio 2008. Later on the project is initialized, the first thing we need to do is define the contract for the service. In other words, what is coming in and going back out. Since we have generated our code using the XSD utility we are going to use the XmlSerializer with our service. The reason is this will make certain our XML formatted the way we intended. While we are at information technology, I've made the service a RESTful type of service. Here is the contract.
[ServiceContract]
public interface IJobService
{[OperationContract]
[XmlSerializerFormat]
[System.ServiceModel.Spider web.WebGet(UriTemplate="/jobs/{type}", RequestFormat=WebMessageFormat.Xml)]
List<Task> GetJobListings(cord type);
}
The contract above has one method GetJobListings(). This method has ii boosted attributes. One, the attribute to marking the method to serialize using the XmlSerializer and 2 the aspect to turn the method into a RESTful service. In other words our service can be accessed like this:
http://localhost/service.svc/jobs/full-time
Now that the contract is setup, we merely need a class to implement this contract on. Here's a quick and dirty implementation.
public class Service1 : IJobService
{#region IJobService Members
public List<Job> GetJobListings(string type)
{
render GetJobs();
}private static Listing<Chore> GetJobs()
{
var jobs = new List<Chore>();
jobs.Add(new Job { JobType= JobType.parttime, Category = JobCategory.Banking, Benefits= "You are on your own.", Clarification="I did something" });
jobs.Add(new Task { JobType= JobType.fulltime, Category = JobCategory.Cyberbanking, Benefits= "You get something." });
jobs.Add(new Job { JobType= JobType.contractor, Category = JobCategory.Banking, Benefits= "Times are tuff, deal with it." });
jobs.Add(new Job { JobType= JobType.fulltime, Category = JobCategory.Banking, Benefits= "How does $700 billion audio?" });
return jobs;
}
0 Response to "How To Get Xsd From Web Service"
Post a Comment