Simplest way to validate Xml against a Xml Schema – level 200

There are plenty of articles out that explaining how to validate Xml, but they all seem to use namespaces or have other factors in them.  I didn’t find one that used plain Xml with no namespace declaration, so I whipped up a little example.  I included the Xml and Xsd inline and load it using a StringReader, but for your purposes, they would probably be in physical files.


            string xsd;


            string xml;


            xsd = @”<xs:schema xmlns:xs=””http://www.w3.org/2001/XMLSchema””&gt;


                        <xs:element name=””address””>


                        <xs:complexType>


                        <xs:sequence>


                        <xs:element name=””name”” type=””xs:string””/>


                        <xs:element name=””street”” type=””xs:string””/>


                        <xs:element name=””city”” type=””xs:string””/>


                        <xs:element name=””country”” type=””xs:string””/>


                        </xs:sequence>


                        </xs:complexType>


                        </xs:element>


                        </xs:schema>”;


            xml = @”<?xml version=””1.0″”?>


                        <address>


                        <name>John Smith</name>


                        <street>109 Abbey Close</street>


                        <city>Hayes</city>


                        <country> UK</country>


                        </address>”;



            XmlValidatingReader   vr   = null;


            vr = new XmlValidatingReader(new XmlTextReader(new StringReader(xml)));


            vr.Schemas.Add(null, new XmlTextReader(new StringReader(xsd)));


            vr.ValidationType = ValidationType.Schema;


            vr.ValidationEventHandler += new ValidationEventHandler(vr_ValidationEventHandler);



            // Validate XML data



            try{


                while(vr.Read());


            }catch{


                Console.WriteLine(“Xml Document is not well-formed.”);


            }finally{


                vr.Close();


            }

2 comments

  1. Jitendra kumar

    Hi sir,

    I tried to use your code in my application but it gives error in the following line.

    vr.ValidationEventHandler += new ValidationEventHandler(vr_ValidationEventHandler);

    I am requesting you to please send me the solution if you got.

    Thanks for help.

    Regards,
    Jitendra kumar
    jkumar@rategain.com

  2. Marlon

    Try using the following code

    private void vr_ValidationEventHandler(object sender, ValidationEventArgs e)
    {
    // Report error(s) to the console…
    Console.WriteLine(e.Exception.Message);
    Console.WriteLine(e.Exception.LineNumber);
    }

Comments are closed.