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>

You might also like...

Comments

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.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“To iterate is human, to recurse divine” - L. Peter Deutsch