Getting acquainted with xsd

…I had to define a REST interface, returning XML data. I already did such things before, but I’ve hesitated to learn the XSD syntax for all the usual reasons: yet another useless language, you can’t express with it all the requirements to the data anyway etc, etc. So I’ve usually created my C# classes, serialized them to XML, generated an XSD from it, sent it out to the other party and forgot about it.

This time, I decided to give it a try. Partly because I didn’t really liked the XML you get from the XmlSerializer in C#. And partly because I’ve got to see some specifications of XML structures done by others, and I’ve been impressed by clarity and professional look of defining XML-Elements not in terms of C# classes and types, but using XPath and XSD.
So I did it this way. I’ve created a fake REST server and written responses of its methods in XML files (one file per method). I’ve written the responses manually, freely replacing the tags and structure until I liked it. Then, I’ve let Visual Studio to generate XSD automatically for each of this XML snippets. Finally, I’ve combined all the snippets into one XSD and factored out common types. That’s easier as one may think, because of intellisence and of build-in help system. Besides that, there are not so much concepts in XSD to learn, it is possible to learn the most of them in a day or two.
When I had my hand-crafted XSD file ready, I’ve written a client calling all of the fake REST methods and checking the responses against the schema. It is not really straightforward, but there is a build-in class for that.
When I had all of my REST-tests in the green state, I could easy incorporate changes requested by the customer (and there are plenty of them, at the end of the day not more than 40% of the original schema survived). For every change, I’ve changed the schema first, then run the REST-tests to see a couple of them turned red, then fixed the fake REST methods and run the tests to see them green again. Thus I could keep XSD-snippets defining elements and XML-snippets showing an example of a such element perfectly in sync.

Leave a Reply