validate a xml file against xsd schema in c#

For various reason we have to use XML file as our data source,  To verify the format of data we can use XSD file, by validate against a XSD file we can check that we get proper formatted data as we required.

In c# there is some very good library for that
in coding u have to call
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml;

the coding are very simple

first we have to initialize XSD schema

XmlSchemaSet schemas = new XmlSchemaSet(); //intialize schema class
using (FileStream schemastream = File.OpenRead("schemafile.xsd")) //xsd file load
schemas.Add(XmlSchema.Read(schemastream, new ValidationEventHandler(OnValidate)));//create event for schema
schemas.Compile(); //build up the schema

Now we have to take xml file for validating against our initialized schema
XmlDocument doc = new XmlDocument();
doc.Load("xmlfile.xml"); //load xml
doc.Schemas = schemas; // take schema
doc.Validate(OnValidate); // validate schema

doc.Validate(OnValidate) it do the main job in validation.
OnValidate is a method whiche get validation errors in its event and take action,
a user can write that function like below, we want to show the error in list box which named as ErrorList1, so customized function will be .

void OnValidate(object sender, ValidationEventArgs e)
if (e.Message.Contains("''") && e.Message.Contains("MinLength"))
string s = "'";
string[] m = e.Message.Split(s.ToCharArray());
ErrorList1.Items.Add(m[1] + " field is required");
else if(e.Message.Contains("cannot contain text")) {
string s = " ";
string[] m = e.Message.Split(s.ToCharArray());
int i = m.Length;
ErrorList1.Items.Add("unwanted text before "+m[i] + " element");
else if (e.Message.Contains("''")) { }
catch (Exception v) { ErrorList1.Items.Add("Error in validation"); }

. In ValidationEventArgs e provide the error message. by using the event value we can get error type and error position, some of the displayed there.

Another tips, if u want to write the xml instead of loading u have to just write
doc.LoadXml(TextBox1.Text); instead of doc.Load("xmlfile.xml")

hope that much will help some


About kishordgupta

A software developer
This entry was posted in C#, DATABASE and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your 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