I had an XML file that controlled much of my application and I wanted to be able to validate it and get some Intellisense to making edits a lot easier. I used XSD validation which works great for my design-time needs, but note that the Silverlight libraries don’t have the code to validate it at runtime. This is fine for my current situation, but may be a problem later.
Here is how I got it working:
1. Add an XSD to the project (Add New Item -> XML Schema)
2. Visual Studio 2010 has a lot of tools for visualizing and reporting on the schema, but I found it easiest just to go to the editor by clicking "Use the XML Editor to view and edit the underlying XML schema file"
3. Build the XSD. Since I was new to XSD, a couple sites were pretty helpful. http://www.learn-xml-schema-tutorial.com/ and http://www.w3schools.com/Schema/ Below is a very simplistic XSD that requires the XML have a list of customers. Each customer will have a customerType attribute that has to be "internal" or "external", an optional firstName, and a required lastName.
4. On your XML file, go to the Properties window and edit Schemas. You’ll need to browse to where your XSD is to associate it.
5. Edit the root node of the XML file to use the right default namespace
<?xml version="1.0" encoding="utf-8" ?> <customers xmlns="http://tempuri.org/MySchema.xsd"> </customers>
6. Now Intellisense will work and help you enter the right values. You’ll get compiler warnings if your XML does not conform to the schema
7. There’s one complication with this – if you want to read the XML file in as an XDocument, you’ll now have to include the namespace when referencing the Nodes. For example, doc.Descendents(XName.Get(“customers”,”http://tempuri.org/MySchema.xsd”)). To avoid this, I used some code from http://www.everydayinternetstuff.com/2009/12/default-namespace-for-linq-to-xml-query/ that will just strip the namespace info from the XML.