Thursday, July 12, 2012

Validating Xml document against Xml Schema

Purpose

Used for validating an Xml Document.

Xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="MyDocumentRoot">
    <xs:complexType>
      <xs:all>
        <xs:element name="FirstRequiredElementUnder" type="xs:string" />
        <xs:element name="SecondRequiredElementUnder " type="xs:string" />
        <xs:element name="ThirdOptionalElement" maxOccurs="1" minOccurs="0"></xs:element>
      </xs:all>
    </xs:complexType>
  </xs:element>
</xs:schema>

Conforming Xml Documents

<MyDocumentRoot>
  <FirstRequiredElementUnder>some text</FirstRequiredElementUnder>
  < SecondRequiredElementUnder >some text</ SecondRequiredElementUnder>
  <ThirdOptionalElement>some text</ThirdOptionalElement>
</MyDocumentRoot>


<MyDocumentRoot>
  <FirstRequiredElementUnder>some text</FirstRequiredElementUnder>
  < SecondRequiredElementUnder >some text</ SecondRequiredElementUnder>
</MyDocumentRoot>

Code to Validate Xml Document against Schema

// setup reader settings to validate against the Xml schema
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("", XmlReader.Create(new StringReader( xmlSchemaText )));
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandlerForXml);

// read the Xml document with schema settings and execute the validation
XmlReader reader = XmlReader.Create(new StringReader(xmlDocumentText),  settings);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
xmlDoc.Validate(ValidationEventHandlerForXml );

...

void  ValidationEventHandlerForXml  (object sender, ValidationEventArgs e)
{
  switch (e.Severity)
  {
      case XmlSeverityType.Error:
        throw new Exception(e.Message);              
  }          
}