XML document validation against XML schema : Schema Validation « XML « ASP.NET Tutorial






<%@ Page Language="C#" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Schema" %>

<script runat="server">
   private XmlTextReader reader;
   private XmlValidatingReader validator;
   
   void Page_Load(Object Sender, EventArgs e) {
      try {
         reader = new XmlTextReader(Server.MapPath("Data.xml"));
         validator = new XmlValidatingReader(reader);
         validator.ValidationType = ValidationType.XDR;
         
         validator.ValidationEventHandler += new ValidationEventHandler(this.ShowError);
         
         while (validator.Read()) {
         }
      } catch (Exception ex) {
         Response.Write("Error accessing XML file");
      } finally {
         reader.Close();
      }
   }
   
   void ShowError(Object Sender, ValidationEventArgs e) {
      Response.Write("<font color=\"red\">" + e.Message + "<br>");
         
      if (reader.LineNumber > 0) {
         Response.Write("Line: " + reader.LineNumber + " Position: " + reader.LinePosition + "</font>");
      }
   }
</script>

<html><body>

</body></html>

File: Data.xml
<bookstore xmlns="x-schema:Data.xdr">
  <book genre="novel" style="hardcover">
    <title>title 1</title>
    <price>1.5</price>
    <author>
      <first-name>M</first-name>
      <last-name>A</last-name>
    </author>
  </book>

</bookstore>

File: Data.xdr

<?xml version="1.0"?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data" 
        xmlns:dt="urn:schemas-microsoft-com:datatypes">
  <ElementType name="first-name" content="textOnly"/>
  <ElementType name="last-name" content="textOnly"/>
  <ElementType name="name" content="textOnly"/>
  <ElementType name="price" content="textOnly" 
                        dt:type="fixed.14.4"/>
  <ElementType name="author" content="eltOnly" order="one">
    <group order="seq">
      <element type="name"/>
    </group>
    <group order="seq">
      <element type="first-name"/>
      <element type="last-name"/>
    </group>
  </ElementType>
  <ElementType name="title" content="textOnly"/>
  <AttributeType name="genre" dt:type="string"/>
  <AttributeType name="style" dt:type="enumeration"
        dt:values="paperback hardcover"/>
  <ElementType name="book" content="eltOnly">
    <attribute type="genre" required="yes"/>
    <attribute type="style" required="yes"/>
    <element type="title"/>
    <element type="price"/>
    <element type="author"/>
  </ElementType>
 <ElementType name="bookstore" content="eltOnly">
    <element type="book"/>
  </ElementType>
</Schema>








25.5.Schema Validation
25.5.1.XML document validation against XML schema
25.5.2.XML validation