Library code snippets

How to validate an XML file with an XSD file

Utlimately I want to be able to parse an xml STRING with an xsd STRING but this is the best I could do: parsing an xml FILE with an xsd FILE. I basically reworked a console application example in the MSDN help file into a nicer looking ASP.NET Web form example. It tells you if your file is not well-formed and then if it is not valid it lists out the specific reason (like in XMLSpy), quite helpful to find an error in a large XML file as it returns the line number on which the error occurred as well as the tag name. This was done in Visual Studio .NET so to get it to work you will have to change the code around to whatever you want to do. Notice that you have to have the namespace in the root element of the XML file.

validate.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Xml.Schema;

namespace validate
{
   public class WebForm1 : System.Web.UI.Page
   {
       protected System.Web.UI.WebControls.Label Label1;
       protected System.Web.UI.WebControls.Button Button1;
       protected System.Web.UI.WebControls.Label Label3;
       protected System.Web.UI.WebControls.Label TheXml;
       protected System.Web.UI.WebControls.Label Label2;
       protected System.Web.UI.WebControls.Label Output;
       protected System.Web.UI.WebControls.Label Outcome;
       protected System.Web.UI.WebControls.Label TheXsd;
   
       private void Page_Load(object sender, System.EventArgs e)
       {
           //define variables
           TheXml.Text = HttpContext.Current.Server.MapPath("books.xml");
           TheXsd.Text = HttpContext.Current.Server.MapPath("books.xsd");
           Outcome.Text = "";
       }

       private void Button1_Click(object sender, System.EventArgs e)
       {
           //define variables
           Outcome.Text = "<font color=\"green\">Succeeded</font>";
           Output.Text = "";

           //load schema
           XmlSchemaCollection xsc = new XmlSchemaCollection();
           xsc.Add("generic", TheXsd.Text);
           Validate(TheXml.Text, xsc);
       }

       private void Validate(String filename, XmlSchemaCollection xsc)
       {
           XmlTextReader reader = null;
           XmlValidatingReader vreader = null;

           reader = new XmlTextReader (filename);
           vreader = new XmlValidatingReader (reader);
           vreader.Schemas.Add(xsc);
           vreader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
           try
           {
               while (vreader.Read()){}
           }
           catch
           {
               Output.Text = "XML Document is not well-formed.";
           }
           vreader.Close();
       }

       public void ValidationCallBack (object sender, ValidationEventArgs args)
       {
           Outcome.Text = "<font color=\"red\">Failed:</font>";
           Output.Text += "Validation error: <font color=\"red\">" + args.Message + "</font><br>";
       }  


   }
}

Books.xml

<?xml version="1.0"?>
<bookstore xmlns="generic">
   <book genre="autobiography">
       <title>The Autobiography of Benjamin Franklin</title>
       <author>
           <first-name>Ben</first-name>
           <last-name>Franklin</last-name>
       </author>
       <price>89.88</price>
   </book>
   <book genre="novel">
       <title>The Confidence Man</title>
       <author>
           <first-name>John</first-name>
           <last-name>Melville</last-name>
       </author>
       <price>11.99</price>
   </book>
</bookstore>



Books.xsd
---------------------------
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="generic" elementFormDefault="qualified" targetNamespace="generic">
   <xsd:element name="bookstore" type="bookstoreType"/>
   <xsd:complexType name="bookstoreType">
       <xsd:sequence maxOccurs="unbounded">
           <xsd:element name="book" type="bookType"/>
       </xsd:sequence>
   </xsd:complexType>
   <xsd:complexType name="bookType">
       <xsd:sequence>
           <xsd:element name="title" type="xsd:string"/>
           <xsd:element name="author" type="authorName"/>
           <xsd:element name="price" type="xsd:decimal"/>
       </xsd:sequence>
       <xsd:attribute name="genre" type="xsd:string"/>
   </xsd:complexType>
   <xsd:complexType name="authorName">
       <xsd:sequence>
           <xsd:element name="first-name" type="xsd:string"/>
           <xsd:element name="last-name" type="xsd:string"/>
       </xsd:sequence>
   </xsd:complexType>
</xsd:schema>

Comments

  1. 18 May 2009 at 22:01

    Nice post you can read more about validating XML document here Link Text

  2. 01 Jan 1999 at 00:00

    This thread is for discussions of How to validate an XML file with an XSD file.

Leave a comment

Sign in or Join us (it's free).

Edward Tanguay Edward Tanguay updates his personal web site tanguay.info weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.
AddThis

Related podcasts

  • The One With The Maracas ...

    Its the last day of the MVP Summit, the boys dive deep into XML and dynamic language sessions all NDA unfortunately so don't expect them to say anything ... But an interview with Russ Nemhauser uncovers his love for the Mac and concern with some project management methodologies. Brad Abrams gets ...

Events coming up

  • Jul 13

    SmartClient

    California, United States

    A Smart Client is an application that uses local processing, consumes XML Web Services and can be deployed and updated from a centralized server. While the .NET Framework (Windows Forms) and the .

Want to stay in touch with what's going on? Follow us on twitter!