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>
Related articles
Related discussion
-
Help required to know about sync of RFID read tag thru Handheld-sample code in .net
by usha@myrf (0 replies)
-
How to query multiple xml files?
by lamin (0 replies)
-
Tree structures in ASP.NET and SQL Server
by satport (28 replies)
-
Problem in uploading the image using fck editor in asp.net 2.0
by quynt (12 replies)
-
handling special character in xslt's
by bussureddy82 (1 replies)
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 ...
Sorry - gratuitous linking, but did not realise I should have referenced my post thus.
Peace.
!--removed tag-->Thanks for that - very useful.
The problem that I have found is when I am presented with an XML file that does not reference the XSD in the first place; the validation routines pass the document without any excitement! The solution, I found, was to confirm that our required namespace was within the XML doc and then validate the file. See http://skotl.blogspot.com/2009/07/validating-xml-files-against-xsd.html for more info. Scott
!--removed tag-->Nice post you can read more about validating XML document here Link Text
!--removed tag-->This thread is for discussions of How to validate an XML file with an XSD file.