XML Schema validation

bovlk
bovlk used Ask the Experts™
on
Hello,

I've got the code below in ASP.NET 3.5/C#. I pass it a schema file and an XML that does not complain to the XSD at all, yet I don't get the exception. I spent about an hour trying to figure out what's wrong, yet did not come to a solution. Any help is welcome. Thanks

Bolek
XmlSchemaSet schemas = new XmlSchemaSet();

using (FileStream fs = new FileStream( "schema.xsd"), FileMode.Open, FileAccess.Read))
using (XmlReader str = XmlReader.Create(fs))
{
  XmlSchemaAvenue.Add(null, str);
}

try
{
  string xml = ReadXmlFromZipFile( "file.xml");

  XmlReaderSettings xrs = new XmlReaderSettings();
  xrs.ValidationType = ValidationType.Schema;
  xrs.Schemas = schema;
  using (StringReader sr = new StringReader(xml))
  using (XmlReader reader = XmlReader.Create(sr, xrs))
  {
    while (reader.Read()) ;
  }
}
catch (XmlSchemaValidationException)
{
  Error();
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Are you simply trying to validate your XML? If so, you need to add an event handler to the XmlReaderSettings object's ValidationEventHandler event:
public void Test()
{
    XmlSchemaSet schemas = new XmlSchemaSet();

    using (FileStream fs = new FileStream( "schema.xsd"), FileMode.Open, FileAccess.Read))
    using (XmlReader str = XmlReader.Create(fs))
    {
      XmlSchemaAvenue.Add(null, str);
    }

    try
    {
      string xml = ReadXmlFromZipFile( "file.xml");

      XmlReaderSettings xrs = new XmlReaderSettings();
      xrs.ValidationType = ValidationType.Schema;
      xrs.ValidationEventHandler += new ValidationEventHandler(xrs_ValidationEventHandler);
      xrs.Schemas = schema;

      using (StringReader sr = new StringReader(xml))
      using (XmlReader reader = XmlReader.Create(sr, xrs))
      {
        while (reader.Read()) ;
      }
    }
    catch (XmlSchemaValidationException)
    {
      
    }
}

void xrs_ValidationEventHandler(object sender, ValidationEventArgs e)
{
    Error();
}

Open in new window

ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
The handler xrs_ValidationEventHandler will be executed for every validation error the parser encounters.

Author

Commented:
Does not work either.
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Author

Commented:
The handler does not get called at all.
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Did you add line 17 from my post as well?

Author

Commented:
Yes.
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Are you sure your instance document is invalid? The handler fired for me. The handler only fires when an error is encountered. If the document is valid, the handler will never fire.
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Here is the code I used as well as my test documents.
static void Main(string[] args)
{
    (new Program()).Test();
}

System.Data.SqlClient.SqlDataReader reader;

public void Test()
{
    XmlSchemaSet schemas = new XmlSchemaSet();

    using (FileStream fs = new FileStream("test.xsd", FileMode.Open, FileAccess.Read))
    {
        using (XmlReader str = XmlReader.Create(fs))
        {
            schemas.Add(null, str);
        }
    }

    try
    {
        string xml = (new StreamReader("test.xml").ReadToEnd());

        XmlReaderSettings xrs = new XmlReaderSettings();
        xrs.ValidationType = ValidationType.Schema;
        xrs.ValidationEventHandler += new ValidationEventHandler(xrs_ValidationEventHandler);
        xrs.Schemas = schemas;

        using (StringReader sr = new StringReader(xml))
        using (XmlReader reader = XmlReader.Create(sr, xrs))
        {
            while (reader.Read()) ;
        }
    }
    catch (XmlSchemaValidationException)
    {
        System.Diagnostics.Debugger.Break();
    }
}

void xrs_ValidationEventHandler(object sender, ValidationEventArgs e)
{
    System.Diagnostics.Debugger.Break();
}

Open in new window

test.xml
test.xsd
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Also, ValidationEventArgs in the handler has a "Message" property which will tell you why validation failed.

Author

Commented:
OK, your examples work fine. However, if I try the file below, which has even the root element different, it goes without noticing the problem.

Author

Commented:
Here's the file - I forgot to attach it.
workbook.xml
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
I'm sorry, but what is different about the root? I see:

    <workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">

    </workbook>

Author

Commented:
Your XML and XSD have <shiporder> as root, mine has <workbook>. Shouldn't it be detected as schema violation? Obviously, a file with different name of the root node cannot conform to the schema.
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
Ok, I misunderstood what you meant :)  I thought you changed the root node's starting tag to something different than its ending tag to cause an invalid document.

In any event, I believe the reason for this behavior is due to the fact that my sample schema has elements under a different namespace as your sample document. Your instance document's elements are defined under the namespace

    http://schemas.openxmlformats.org/spreadsheetml/2006/main

whereas my schema did not define what the "targetNamespace" was. The schema cannot validate the document because the namespace is different. Adding the following

     targetNamespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main"

 to the schema element yields an error.

Author

Commented:
OK, so is there any way of validating so that if the document has different root and/or namespace, I always get an error, and if it has the same root & namespace, it is validated by the XSD? Of course I can simply find the root node and do the comparison manually, but is there any other way, possibly using the XSD file and XmlReader again?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial