1

This code is not validating the Xml properly Could you please find the mistake.... Even if I am executing with Invalid xml it is not raising any error

using System.Xml;

namespace XmlTryProject
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            XmlReaderSettings readSettings = new XmlReaderSettings();
            readSettings.ValidationType = ValidationType.Schema;
            readSettings.Schemas.Add(null,
     @"C:\Visual Studio 2010\Projects\XmlTry \XmlTryProject\EmployeeXSD.xsd");

            readSettings.ValidationEventHandler +=
                new System.Xml.Schema.ValidationEventHandler(Validater);

            XmlReader xReader = XmlReader.Create(
     @"C:\Visual Studio 2010\Projects\XmlTry\XmlTryProject\EmployeeXML.xml",
                readSettings);

            while (xReader.Read())
            {
                if (xReader.NodeType == XmlNodeType.Element)
                {
                    Console.WriteLine(xReader.Name);
                }
            }
        }

        public static void Validater(object sender,
                             System.Xml.Schema.ValidationEventArgs args)
        {
            Console.WriteLine(args.Message);
        }
    }
}
Kjartan
  • 18,591
  • 15
  • 71
  • 96
thevamsi
  • 39
  • 4
  • I suspect the stackoverflow question will help: http://stackoverflow.com/questions/751511/validating-an-xml-against-referenced-xsd-in-c-sharp – Ross Dargan Dec 21 '12 at 11:19

2 Answers2

3

It looks like you forgot the ValidationFlags:

readSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
readSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
readSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
gdoron
  • 147,333
  • 58
  • 291
  • 367
0

Here is a simple method that uses linq to xml.
The method ValidateXmlFile is a sample of how to use it.

private static void ValidateXmlFile()
{
    using (var xmlFile = File.OpenRead("networkshares.xml"))
    using (var xmlSchemaFile = File.OpenRead("networkshares.xsd"))
    {
        ValidateXml("netuseperdomain.networkshares", xmlSchemaFile, xmlFile);
    }
}

public static void ValidateXml(string targetNamespace, Stream xmlSchema, Stream xml)
{
    var xdoc = XDocument.Load(xml);
    var schemas = new XmlSchemaSet();
    schemas.Add(targetNamespace, new XmlTextReader(xmlSchema));

    xdoc.Validate(schemas, (sender, e) =>
    {
        throw new Exception(e.Message);
    });
}
Jens Granlund
  • 4,950
  • 1
  • 31
  • 31