XML Validate XML Data With the XmlSchemaSet Class
Listing 4. You need to drop this code in a Web form. The XmlSchemaSet class lets you place schemas in a cache so you can use them through the XmlReaderSettings object to validate the XML data. ![]() <%@ 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"; XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(null, xsdFilePath); XmlReader reader = null; XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationEventHandler += new ValidationEventHandler( this.ValidationEventHandler); settings.XsdValidate = true; settings.Schemas = schemaSet; reader = XmlReader.Create(xmlFilePath, 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>XSD Validation using XmlSchemaSet</title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html> |