Validate XML Against XSD [XML SCHEMA] using C#

 In this blog post, we will see how to create an XML schema file for an xml file and how to validate if a certain XML complies to our schema.

First of all, open the XML file in Visual Studio. Right click the solution explorer select add Existing file and select the xml file. Open the file and choose from the menu XML --> Create Schema.
Now you have the schema and the XML file, it is time to write some code to validate the xml file.

                    XmlReaderSettings settings = new XmlReaderSettings();
                    settings.Schemas.Add(null, XSDFILEPATH);
                    settings.ValidationType = ValidationType.Schema;
                    XmlDocument document = new XmlDocument();
                    XmlReader rdr = XmlReader.Create(new StringReader(document.InnerXml), settings);
                isValid = false;

if the validation fails, a private field is set to false (isValid) in which you can check at runtime to see if the status of the validation process.

Hope this helps,

Published 06 November 2008 05:07 PM by haissam


# Vipin Kumar Mallaya said on 30 August, 2009 12:10 PM

This is rally useful code to validate

Not at all Complicated

really easy to understand

its really working

# chandler said on 19 October, 2009 09:13 PM

very helpful yet simple.. just what every example should be.


# Ruju said on 28 October, 2009 03:34 AM

Thanx for the short and efficient code!!

# tomassino said on 24 November, 2009 04:56 PM

thanks a lot! perfect, very simple and working example

# Muhammad Farhan Jamil said on 28 November, 2009 10:33 AM

Simple and working ...

This site



This Blog



  • MaximumASP