Recently, I had to work on a project that saw me using a lot of XML, something I’ve not done for a long time.
The thing was, however, I had a number of XSD files that I then had to use to build parsers for the XML data I was dealing with.
This is not something I’ve not had to do before, however, but it did serve to remind me about something I’d forgotten about that’s built into Visual Studio, and makes handling XML data child’s play.
Visual Studio and the .NET framework come with a useful tool called ‘XSD’. If you click your Start menu, and go to your installed version of Visual Studio, somewhere in the menus you’ll see a link to the ‘Visual Studio Command Line’ tools. Find and click this, so that you have a Visual Studio command line, then type
xsd
and press Return, you should see something similar to the following:
Figure 1: XSD run at the Visual Studio tools prompt (and yes, I do have it in that colour 🙂 )
Although it looks complicated, it’s actually a very easy tool to use.
If you already have an XSD document, you can simply use it to generate C# (or VB) code that will read/write your XML data.
For this article, however, we’re going to create our own.
First, Some Sample XML
To get started, you need to create some XML data you might want to use. For me, I’m just going to do something simple, and create a list of .NET Nuts and Bolts articles, as follows:
<articles> <article> <title>The Singleton Pattern</title> <description>The Singleton pattern is very flexible. Learn to wrap it around your little finger.</description> <link>https://www.codeguru.com/columns/dotnet/ the-singleton-pattern.html</link> </article> <article> <title>Full Screen Video in ASP.NET MVC</title> <description>HTML5 Offers you the capability to do full screen video in your devices.</description> <link>https://www.codeguru.com/columns/dotnet/full-screen-video- in-asp.net-mvc.html</link> </article> <article> <title>Vectors for the C# developer</title> <description>Generic lists (and for that matter, most of the collections......</description> <link>https://www.codeguru.com/columns/dotnet/vectors-for-the- c-developer.html</link> </article> </articles>
Now that we have a snippet of XML, save it somewhere on your hard drive. I’ve called mine ‘articles’xml’.
Open your Visual Studio command line tools window, browse to where you saved your XML file, and then, using the XSD tool, type the following
xsd articles.xml
The XSD tool should report the following:
Figure 2: The output from XSD processing our XML
You’ll notice that the XSD tool has processed our XML data and created an XSD file. XSD files are used to inform XML processors what the XML data they are dealing with should look like.
In our case, the XSD file that’s been generated will inform any parsing code that the XML file starts with “articles”, and contains a series of “article” elements each containing an ‘article’, ‘description’, and ‘link’ element.
If we now run the XSD tool once more, this time on our generated XSD file as follows
xsd articles.xsd /c
We should now see a slightly different message:
Figure 3: The XSD tool can create C sharp code for us
This time, you’ll note the message states XSD has created a C sharp source file for us.
What’s happened her, is that the XSD tool has processed the generated XSD rules file, and used that to build us a .NET class that can read and write our XML data. By using this class, we now can create a simple console mode application to handle our XML file.
Create yourself a simple console mode application in Visual Studio. Then, add the class that the XSD tool created for you to your project.
After you add the class to your project, make sure your Program.cs file looks as follows:
using System.IO; using System.Xml.Serialization; namespace xmlxsdrefresh { class Program { static void Main(string[] args) { articles myArticles = new articles {Items = new articlesArticle[3]}; myArticles.Items[0] = new articlesArticle { title = "The Singleton Pattern", description = "The Singleton pattern is very flexible. Learn to wrap it around your little finger.", link = "https://www.codeguru.com/columns/ dotnet/the-singleton-pattern.html" }; myArticles.Items[1] = new articlesArticle { title = "Full Screen Video in ASP.NET MVC", description = "HTML5 offers you the capability to add full screen video in your devices. Read along and learn how to leverage this new feature.", link = "https://www.codeguru.com/columns/dotnet/ full-screen-video-in-asp.net-mvc.html" }; myArticles.Items[2] = new articlesArticle { title = "Vectors for the C# Developer", description = "Generic Lists (and, for that matter, most of the collections in the 'System.Collections' namespace) are already generics aware.", link = "https://www.codeguru.com/columns/dotnet/ vectors-for-the-c-developer.html" }; var serializer = new XmlSerializer(typeof(articles)); using (var stream = new StreamWriter("newarticles.xml")) { serializer.Serialize(stream, myArticles); } } } }
You now should be able to compile and run your program, which won’t produce any output on your console, but it should create an XML file in the folder that your application is running from. The contents of this XML file should look the same as the XML data I showed earlier in this post.
Figure 4: The XML file produced by our program
You can easily go the other way, too, and load the data from an XML file that matches the format, back into the class created by the XSD tool. Change your Program.cs file so that it reads:
using System.IO; using System.Xml.Serialization; namespace xmlxsdrefresh { class Program { static void Main(string[] args) { XmlSerializer ser = new XmlSerializer(typeof(articles)); articles myArticles = ser.Deserialize(new FileStream("newarticles.xml", FileMode.Open)) as articles; } } }
If you now run this with the XML file you generated in the same folder, you should see that it pulls the data back in, and deconstructs it back to a set of objects you can use:
Figure 5: Visual Studio showing our program with the XML data loaded back in
Using XSD makes it almost child’s play to manipulate XML data. You also could add something like JSON.Net (which I’ve also covered in previous posts) and turn the de-serialized data into JSON for use in JavaScript-based applications.
I find and document hidden gems and useful tools in .NET, so you don’t have to waste time hunting for them. iI you’ve heard about a strange tool or API but don’t know anything about it, why not come hunt me down on twitter as @shawty_ds, or in the Lidnug .NET users group that I help run on Linked-in? I’ll likely write a post about it.