[C# – XML] Validation Using the XmlSchemaSet

XML schema is the recommended way of validating XML documents and the replacement of DTD. “System.Xml.Schema.XmlSchemaSet” is a collection of schemas and improves performance by caching schemas in memory.

 

1. XmlSchemaSet Object

  • Create an “XmlSchemaSet” object
  • Add a schema to the object using one of the “Add()” methods

 

2.  XmlReaderSettings Object

  • Create an “XmlReaderSettings” object
  • Set the “ValidationType” property to “Schema
  • Set the “Schemas” property to the instance of “XmlSchemaSet

 

3. Validation Event Handler

  • Create a validation event handler method with 2 parameters: (object sender, ValidationEventArgs args)
  • Add the event handler to the “ValidationEventHandler” event of the “XmlReaderSettings” object

 

4. XmlReader

  • Create an “XmlReader” object using the static “Create” method

 

5. Schema Sample

<?xml version="1.0" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  targetNamespace="http://www.book.com"
  xmlns="http://www.book.com"
  elementFormDefault="qualified" >

  <xs:element name="book">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="title" type="xs:string" />
        <xs:element name="author" type="xs:string" />
      xs:sequence>
      <xs:attribute name="isbn" type="xs:string" use="required" />
    </xs:complexType>
  </xs:element>
</xs:schema>

 

6. XML Sample

<?xml version="1.0" ?>
<book isbn="157281055"
  xmlns="http://www.book.com"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.book.com book.xsd" >
  <title>The Lord of the Rings</title>
  <author>J.R.R. Tolkien</author>
</book>

 

7. C# Sample Code

public static void ReadXMLwithXSD()
{
  // Schema
  XmlSchemaSet sc = new XmlSchemaSet();
  sc.Add("http://www.book.com", "book.xsd");

  // Set the validation settings.
  XmlReaderSettings settings = new XmlReaderSettings();
  settings.ValidationType = ValidationType.Schema;
  settings.Schemas = sc;
  settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
  settings.IgnoreWhitespace = true;

  // Create the XmlReader object.
  XmlReader reader = XmlReader.Create("bookschema.xml", settings);

  // Parse the file.
  while (reader.Read())
  {
    System.Console.WriteLine("{0}, {1}: {2} ", reader.NodeType, reader.Name, reader.Value);
  }
}

private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
  if (e.Severity == XmlSeverityType.Warning)
    Console.WriteLine("Warning: Matching schema not found.  No validation occurred." + e.Message);
  else // Error
    Console.WriteLine("Validation error: " + e.Message);
}

Feel free to change XSD or XML and look at what kind of errors you get.

For example, if you remove the attribute “isbn” line, you will get an error (“The required attribute ‘isbn’ is missing.”) but the document will be still be parsed till the end.

One thought on “[C# – XML] Validation Using the XmlSchemaSet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s