XML / XSD Validation


I know, I should probably have a separate page for XML and C#, but friends trust me there are plenty out there and I’d very much not like to simply copy and paste it all, rather to share URLs. The resources that helped me most were [drum-roll] MSDN & W3Schools.com (http://xmlmaster.org is also a strong competitor though – IMO )

References :

Alright, so w/o further due, assuming you’ve some understanding of XSD, ( of-course ) XML, let’s see how can we validate them. I’ve also posted couple of full fledged xml-xsd pairs so you can catch up that part above later / skip it / refer if you’ve blockers. Either-way let’s move on to more meaty stuff.

So I’ve a file called XMLFile1.xml as following : (based on w3schools.com’s example) :

<?xml version="1.0" encoding="utf-8" ?>
<notes
  xmlns="http://schemas.microsoft.com/fakes/2011/"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemalocation="http://schemas.microsoft.com/fakes/2011/ XMLSchema1.xsd">
  <note>
	<heading>Note 1 header</heading>
	<body>Here is a note to Tove from Jani</body>
  </note>
  <note>
	<heading>Note 2</heading>
	<body>The content for note 2 goes here</body>
  </note>
</notes>

And, XMLSchema1.xsd :

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema
   id="XMLSchema1"
   elementformdefault="qualified"
   xmlns="http://schemas.microsoft.com/fakes/2011/ XMLSchema1.xsd"
   xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="notes">
	<xs:complexType>
		<xs:sequence>
		<xs:element name="note" maxOccurs="unbounded" minOccurs="0">
			<xs:complexType>
			<xs:sequence>
				<xs:element type="xs:string" name="heading"/>
				<xs:element type="xs:string" name="body"/>
			</xs:sequence>
			</xs:complexType>
		</xs:element>
		</xs:sequence>
	</xs:complexType>
	</xs:element>
</xs:schema>
Now let’s talk about how to validate it ? I’ve created a console project in Microsoft Visual Studio and added the filed above to my project ( feeling lazy so added directly to ~/bin/debug 😛 )
static void Main(string[] args)
{
	try
	{
		XmlTextReader xmlTextReader = new XmlTextReader("XMLSchema1.xsd");
		XmlSchema mySchema = XmlSchema.Read(xmlTextReader, null);
		StringWriter stringWriter = new StringWriter();
		mySchema.Write(stringWriter);

		XmlSchemaSet schemas = new XmlSchemaSet();
		schemas.Add(mySchema);

		XDocument xDoc = XDocument.Load("XMLFile1.xml");
		bool err = false;
		xDoc.Validate(schemas, (o, e) =>
		{
			Console.WriteLine(e.Message);
			err = true;
		});
		Console.WriteLine(err ? "Invalid" : "Valid");
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.Message);
	}
}
That’s it, Ctrl + F5 ! o/p : “Valid”. Cool. Now you may want to try some different data-types (like DateTime)in your schema to play with it.
Here are some more resources for DateTime :

Now let me show you some black magic ! Open XSD file in Visual Studio (tested in 2010 & 13) this time do not Press F7 (nor you need to select view code from context menu). Right click on XSD file ==> “Open With …” ==> Select “XML Schema Designer”. When the following screen shows up. Rather, Either View ==> XML Schema Explorer or simply click on “XML Schema Explorer” link.

Upon recursively expanding you should see “ notes” Right Click ==> Generate Sample XML. Isn’t that nice ? Cool.


Next up we’ll now tightened up some validation rules :

using System;
using System.Xml;
using System.Xml.Schema;

namespace XmlSchemaChange
{
	class Program
	{
		static void Main(string[] args)
		{
			try
			{
				XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
				xmlReaderSettings.ValidationType = ValidationType.Schema;
				xmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
				xmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
				xmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
				xmlReaderSettings.CloseInput = true;
				xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(xmlReaderSettings_ValidationEventHandler);

				XmlReader reader = XmlReader.Create("XMLFile1.xml", xmlReaderSettings);
				while (reader.Read()) ;

			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
		}

		private static void xmlReaderSettings_ValidationEventHandler(object sender, ValidationEventArgs e)
		{
			if (e.Severity == XmlSeverityType.Warning)
				Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + e.Message);
			else
				Console.WriteLine("\tValidation error: " + e.Message);
		}
	}
}
I’d pause here for now. But in future I’d love to have some addendum for XSD. That’s it for now. Now let me upload the screen shots before I forget 😀 😛
Advertisements

Published by

Aarsh Talati

Software Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s