none
My XML validation doesn't seem to work

    Question

  • Hi,

    Im trying to create a XML validator in C# (have read a couple of inputs here), but aren't having any luck with the validation part of the code.

    Am I missing something?

    Each time I choose a file for validation the code does it trick but it doen't seem to really validate anything.

     

      private void validationCallback(object sender, ValidationEventArgs e)
      {
       success = false; //SCHEMA VALIDATION FAILED
       
       if(e.Severity == XmlSeverityType.Warning)
       {
        writeRtLog("Schema Validation Varning: " + e.Message);
       }
       else if(e.Severity == XmlSeverityType.Error)
       {
        writeRtLog("Schema Validation Error: " + e.Message);
       }
    
       errors++;
      }
    

     

     

    <br/>private bool validateXML(string xmlPath)
      {
        string xsdPath = null;
    
        textBox3.Text.ToUpper();
        if (textBox3.Text.IndexOf(".XSD") >= 0)
        {
         xsdPath = textBox3.Text;
        }
        else
        {
         xsdPath = @"c:\testSchema1.xsd";
        }
    
        writeRtLog("Schema file used: " + xsdPath);
    
        XmlReader xsd = new XmlTextReader(xsdPath);
        XmlSchemaSet schema = new XmlSchemaSet();
        schema.Add(null, xsd);
    
        XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
        xmlReaderSettings.ValidationType = ValidationType.Schema;
        xmlReaderSettings.Schemas.Add(schema);
        xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(validationCallback);
    
        XmlTextReader xmlTextReader = new XmlTextReader(xmlPath);
        XmlReader xmlReader = XmlReader.Create(xmlTextReader, xmlReaderSettings);
    
        while (xmlReader.Read()) ;
        xmlReader.Close();   
    
       return success;
      }
    

     

    It doesn't seem like the validation is taking place.

    Tests:

    test.xml against testSchema1.xsd

    Thursday 19 maj 00:00:00 Validation of XML against schema (XSD) starting...
    Thursday 19 maj 00:00:00 on C:\test.xml
    Thursday 19 maj 00:00:00 Schema file used: c:\testSchema1.xsd
    Thursday 19 maj 00:00:00 XML file has been successfully validated against the schema

    invoice.xml against testSchema1.xsd

    Thursday 19 maj 00:00:00 Validation of XML against schema (XSD) starting...
    Thursday 19 maj 00:00:00 on C:\invoice.xml
    Thursday 19 maj 00:00:00 Schema file used: c:\testSchema1.xsd
    Thursday 19 maj 00:00:00 XML file has been successfully validated against the schema

    *testSchema1.xsd:

     

    <?xml version="1.0" encoding="utf-8" ?>
    <xsd:schema id="Sis" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <xsd:complexType name="PersonalDetails">
     <xsd:sequence>
      <xsd:element name="FirstName" type="xsd:string" minOccurs="1" />
      <xsd:element name="MiddleName" type="xsd:string" />
      <xsd:element name="LastName" type="xsd:string" />
     </xsd:sequence>
     </xsd:complexType>
    
     <xsd:complexType name="StudentType">
     <xsd:sequence>
      <xsd:element name="StudentID" type="xsd:int" />
      <xsd:element name="AcademicDetails" type="xsd:string" />
      <xsd:element name="PersonalDetails" type="PersonalDetails" />
     </xsd:sequence>
     </xsd:complexType>
    
     <xsd:element name="Sis">
     <xsd:complexType>
      <xsd:sequence>
      <xsd:element name="Student" type="StudentType" />
      </xsd:sequence>
     </xsd:complexType>
     </xsd:element>
    </xsd:schema>
    

     

    test1.xml

     

    <Sis>
    <Student>
     <StudentID>10042325</StudentID>
     <AcademicDetails>2008-2009</AcademicDetails>
     <PersonalDetails>
     <FirstName>Vijay</FirstName>
     <MiddleName>Laxmanrao</MiddleName>
     <LastName>Jadhav</LastName>
     </PersonalDetails>
    </Student>
    </Sis>
    

     

    invoice.xml (totally different XML)

     

    <?xml version="1.0" encoding="WINDOWS-1252"?>
    <inv:invoices xmlns:inv="http://test.se/fng/common/xml/invoice">
     <inv:organisation>
      <inv:organisationName>Test AB</inv:organisationName>
      <inv:organisationNumber>55</inv:organisationNumber>
      <inv:streetAddress>Box 47</inv:streetAddress>
      <inv:postalCode>10074</inv:postalCode>
      <inv:cityAddress>STURUP</inv:cityAddress>
      <inv:countryCode>SE</inv:countryCode>
      <inv:vatNumber>SE556</inv:vatNumber>
      <inv:BankAccountNumber>6155032</inv:BankAccountNumber>
      <inv:PostGiroNumber>24</inv:PostGiroNumber>
      <inv:BankGiroNumber>483</inv:BankGiroNumber>
    
    ...
    

    Any ideas? Let me know if you need more info.

     

    Ps. The Sis-XML isn't mine. I've 'borrowed' it from a post, in order to create errors when validating against my invoice.xml Ds.

     

     


    Thursday, May 19, 2011 12:49 PM

Answers

  • Hi Keysersose

    Try this staff, it works well for me. I just created C:\temp\Student.xml and C:\temp\Schema1.xsd and tried the staff

    using System;
    using System.Xml;
    using System.Xml.Schema;
    
    namespace MSDN
    {
      class Program
      {
        static bool validation = true;
        static void Main(string[] args)
        {
          XmlSchemaSet sc = new XmlSchemaSet();
          sc.Add(null, "file:///C:/temp/Schema2.xsd");
    
          // Set the validation settings.
          XmlReaderSettings settings = new XmlReaderSettings();
          settings.ValidationType = ValidationType.Schema;
          settings.Schemas = sc;
          settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
    
          // Create the XmlReader object.
          XmlReader reader = XmlReader.Create(@"C:\temp\Student.xml", settings);
    
          // Parse the file. 
          while (reader.Read()) ;
    
          if (validation==true)
          {
            Console.WriteLine("The Xml content is valid");
          }
    
          Console.ReadLine();
        }
        // Display any validation errors.
        private static void ValidationCallBack(object sender, ValidationEventArgs e)
        {
          validation = false;
          Console.WriteLine("Validation Error: {0}", e.Message);
        }  
      }
    }
    
    

    Try to change a liitle bit in the schema then you wil be noticed then that something is wrong

     


    The complexity resides in the simplicity Follow me at: http://smartssolutions.blogspot.com
    Tuesday, May 24, 2011 5:37 PM

All replies

  • hi,

    take a look at Validating XML Data with XmlReader and XmlDocument.Validate Method (ValidationEventHandler).


    Microsoft MVP Office Access
    https://mvp.support.microsoft.com/profile/Stefan.Hoffmann
    Thursday, May 19, 2011 1:04 PM
  • Hi KeyserSoze,

    Have you solved this issue?

    If not , you can try the code provided by the following link:

    http://www.codeproject.com/KB/XML/xmlvalidator.aspx

    This link tells about how to create a simple xml validator.

    If you still have any further concern about this issue, please let us know , we will try our best to help solve it.

     

    Best regards,

    Lucy


    Lucy Liu [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, May 24, 2011 8:01 AM
    Moderator
  • I don't seem to see your validation rules though.

     

    chanmm


    chanmm
    Tuesday, May 24, 2011 12:44 PM
  • Hi Keysersose

    Try this staff, it works well for me. I just created C:\temp\Student.xml and C:\temp\Schema1.xsd and tried the staff

    using System;
    using System.Xml;
    using System.Xml.Schema;
    
    namespace MSDN
    {
      class Program
      {
        static bool validation = true;
        static void Main(string[] args)
        {
          XmlSchemaSet sc = new XmlSchemaSet();
          sc.Add(null, "file:///C:/temp/Schema2.xsd");
    
          // Set the validation settings.
          XmlReaderSettings settings = new XmlReaderSettings();
          settings.ValidationType = ValidationType.Schema;
          settings.Schemas = sc;
          settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
    
          // Create the XmlReader object.
          XmlReader reader = XmlReader.Create(@"C:\temp\Student.xml", settings);
    
          // Parse the file. 
          while (reader.Read()) ;
    
          if (validation==true)
          {
            Console.WriteLine("The Xml content is valid");
          }
    
          Console.ReadLine();
        }
        // Display any validation errors.
        private static void ValidationCallBack(object sender, ValidationEventArgs e)
        {
          validation = false;
          Console.WriteLine("Validation Error: {0}", e.Message);
        }  
      }
    }
    
    

    Try to change a liitle bit in the schema then you wil be noticed then that something is wrong

     


    The complexity resides in the simplicity Follow me at: http://smartssolutions.blogspot.com
    Tuesday, May 24, 2011 5:37 PM
  • Hello,

    I've already answered a similar question : http://social.msdn.microsoft.com/Forums/en-US/xmlandnetfx/thread/fe1c7ea5-011e-4088-9752-a487896c4e76

    Eventually, you should better ask in XML forum to get fast answers : http://social.msdn.microsoft.com/Forums/en-US/xmlandnetfx/threads

    Kind regards,


    aelassas.free.fr
    Tuesday, May 24, 2011 6:43 PM