XML • Validate DOM XML Data

Listing 5. Place this code in a Web form. In this example, you use the pipelining approach to read an XmlDocument object into an XmlNodeReader object. Once the XML data is available in the XmlNodeReader object, you can validate it against the XSD schema file. This code gives a "Validation Failed" error message because it adds a new, nonexistent attribute in the XSD schema to the XmlDocument.

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

<script runat="server">
   private StringBuilder builder = new StringBuilder();
   void Page_Load(object sender, EventArgs e)
   {
      string xmlFilePath = Request.PhysicalApplicationPath + 
         @"\App_Data\Authors.xml"; 
      string xsdFilePath = Request.PhysicalApplicationPath + 
         @"\App_Data\Authors.xsd";
      XmlDocument xmlDoc = new XmlDocument();
      xmlDoc.Load(xmlFilePath);
      XmlElement authorElement = (XmlElement)
      xmlDoc.DocumentElement.SelectSingleNode
         ("//authors/author[au_id='172-32-1176']");
      authorElement.SetAttribute("test", "test");
      XmlNodeReader nodeReader = new XmlNodeReader(xmlDoc);
      XmlReader reader = null;
      XmlReaderSettings settings = new XmlReaderSettings();
         settings.ValidationEventHandler += new 
            ValidationEventHandler(
            this.ValidationEventHandler); 
         settings.XsdValidate = true;
         settings.Schemas.Add(null, 
            XmlReader.Create(xsdFilePath));
         reader = XmlReader.Create(nodeReader, settings);
         while (reader.Read()) 
      {
      }
      if (builder.ToString() == String.Empty)
         Response.Write(
            "Validation completed successfully.");
      else
         Response.Write("Validation Failed. <br>" + 
            builder.ToString());
   }

   void ValidationEventHandler(object sender, 
      ValidationEventArgs args)
   {
      builder.Append("Validation error: " + args.Message + 
         "<br>");
   }

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   <title>DOM Validation</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
   </div>
   </form>
</body>
</html>