none
Issue with Validating an Xml with the Schema Xsd RRS feed

  • Question

  • Hi Experts

    I am trying to validate the xml with the Schema xsd by using the below code:

    namespace Test_XmlValidation
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    XmlReaderSettings settings = new XmlReaderSettings();
                    settings.Schemas.Add("http://schemas.com/MySchema", "MySchema.xsd");
                    settings.ValidationType = ValidationType.Schema;

                    XmlReader reader = XmlReader.Create("MySchema.xml", settings);
                    XmlDocument document = new XmlDocument();
                    document.Load(reader);

                    ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

                    // the following call to Validate succeeds.
                    document.Validate(eventHandler);

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

            static void ValidationEventHandler(object sender, ValidationEventArgs e)
            {
                switch (e.Severity)
                {
                    case XmlSeverityType.Error:
                        Console.WriteLine("Error: {0}", e.Message);
                        break;
                    case XmlSeverityType.Warning:
                        Console.WriteLine("Warning {0}", e.Message);
                        break;
                }

            }
        }
    }

    The content of my Xml files look like:

    <Request xmlns="http://schemas.com/MySchema12"></Request>

    Notice that the namespace of xml is not correct.

    Even then the above code is not throwing error and validating the xml successfully.

    In Short, i want to validate the xml namespace against a schema.

    Can someone point me what is the issue over here?


    Deepak Sanghi Happy Biztalking.........

    Wednesday, May 2, 2012 10:42 AM

Answers

  • That does not go to the catch block, because of the ValidationEventHandler is run and no exception is not thrown. If you want to raise exception, then you need to throw it by yourself from validation event handler.

    Does the validation event handler get invoked? In my environment it does, so exception might be created as follows:

            static void ValidationEventHandler(object sender, ValidationEventArgs e)
            {
                switch (e.Severity)
                {
                    case XmlSeverityType.Error:
                        Console.WriteLine("Error: {0}", e.Message);
                        break;
                    case XmlSeverityType.Warning:
                        Console.WriteLine("Warning {0}", e.Message);
                        break;
                }
    
                throw new XmlException("XML data is not valid.");
    
            }

    • Marked as answer by Deepak sanghi Thursday, May 3, 2012 7:01 AM
    Thursday, May 3, 2012 4:49 AM

All replies

  • You could use XmlValidatingReader class

    http://msdn.microsoft.com/en-us/library/system.xml.xmlvalidatingreader.aspx

    Read this article first about limiations of Validating Schemas.

    http://msdn.microsoft.com/en-us/magazine/cc188918.aspx


    jdweng

    Wednesday, May 2, 2012 11:44 AM
  • Joel

    Thanks For the response.

    I tried the XMLValidatingReader also but same result.


    Deepak Sanghi Happy Biztalking.........

    Wednesday, May 2, 2012 12:16 PM
  • Set the validation event handler to the XmlReaderSettings and perform validation when loading XML from reader. See my code changes below:

        class Program
        {
            static void Main(string[] args)
            {
            
                 try
                 {
                     XmlReaderSettings settings = new XmlReaderSettings();
                     settings.Schemas.Add("http://schemas.com/MySchema", "request.xsd");
                     settings.ValidationType = ValidationType.Schema;
                     settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
    
                     // set validation handler
                     settings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ValidationEventHandler);
     
                    XmlReader reader = XmlReader.Create("request.xml", settings);
                     XmlDocument document = new XmlDocument();
    
                     // validate when loading thru reader
                     document.Load(reader);
     
                    //ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
     
                    // the following call to Validate succeeds.
                     //document.Validate(eventHandler);
     
                 
                }
                 catch (Exception ex)
                 {
                     Console.WriteLine(ex.Message);
                 }
    
                 Console.WriteLine("Done...");
                 Console.ReadKey();
            }
    
            static void ValidationEventHandler(object sender, ValidationEventArgs e)
            {
                switch (e.Severity)
                {
                    case XmlSeverityType.Error:
                        Console.WriteLine("Error: {0}", e.Message);
                        break;
                    case XmlSeverityType.Warning:
                        Console.WriteLine("Warning {0}", e.Message);
                        break;
                }
    
            }
     
    
        }

    My schema is following:

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema attributeFormDefault="unqualified" 
               elementFormDefault="qualified" 
               targetNamespace="http://schemas.com/MySchema" 
               xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="request" />
    </xs:schema>
    
    

    XML is:

    <?xml version="1.0" encoding="utf-8" ?>
    <request xmlns="http://schemas.com/MySchema12"></request>

    Wednesday, May 2, 2012 6:11 PM
  • Thursday, May 3, 2012 3:12 AM
  • Deepak,

    You can also check:

    http://www.codeproject.com/Articles/8781/C-XML-Schema-Validator


    Regards, http://shwetamannjain.blogspot.com

    Thursday, May 3, 2012 3:14 AM
  • Sam

    I have tried your code, but it does not work. For wrong namespace also it is getting passed i.e. catch block is not getting executed.

    Thanks

    Deepak Sanghi


    Deepak Sanghi Happy Biztalking.........

    Thursday, May 3, 2012 4:41 AM
  • That does not go to the catch block, because of the ValidationEventHandler is run and no exception is not thrown. If you want to raise exception, then you need to throw it by yourself from validation event handler.

    Does the validation event handler get invoked? In my environment it does, so exception might be created as follows:

            static void ValidationEventHandler(object sender, ValidationEventArgs e)
            {
                switch (e.Severity)
                {
                    case XmlSeverityType.Error:
                        Console.WriteLine("Error: {0}", e.Message);
                        break;
                    case XmlSeverityType.Warning:
                        Console.WriteLine("Warning {0}", e.Message);
                        break;
                }
    
                throw new XmlException("XML data is not valid.");
    
            }

    • Marked as answer by Deepak sanghi Thursday, May 3, 2012 7:01 AM
    Thursday, May 3, 2012 4:49 AM
  • Hi Sweta

    Thanks for the response. however,these links does not fit the bill. I am trying to validate xml having wrong namespace and xml is getting validated inspite of wrong namespace.

    Thanks

    Deepak Sanghi


    Deepak Sanghi Happy Biztalking.........

    Thursday, May 3, 2012 5:12 AM