Thursday, April 26, 2007

Validate XML against your schema XSD

Hi - This post is basically to demenstrate how you can validate your XML input against a specified XML schema. The sample below uses new .net 2.o objects rather than obsolete .net 1.1 objects. I have commented few obsolete objects to highlight the differences.

using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;

namespace ConsoleApplication3
{
///
/// Summary description for Class1.
///


class Class1
{
///
/// The main entry point for the application.
///


System.Boolean m_success;
[STAThread]
static void Main(string[] args)
{

//XmlValidatingReader reader = null; //obsolete in .net 2
XmlReader reader1 = null;

//XmlSchemaCollection myschema = new XmlSchemaCollection(); //obsolete in .net 2
XmlSchemaSet myschema1 = new XmlSchemaSet();
ValidationEventHandler eventHandler = new ValidationEventHandler(Class1.ShowCompileErrors);

try
{
//Create the XML fragment to be parsed.

// String xmlFrag = "YOUR XML string here" ;

//Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

//Implement the reader.
//reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context); //obsolete in .net 2.0
XmlReaderSettings rs = new XmlReaderSettings();

rs.ValidationType = ValidationType.Schema;
myschema1.Add("http://www.newmarketinc.com", Server.Mappath("DirectBook.xsd"));
rs.Schemas.Add(myschema1);
StringReader srXml = new StringReader(xmlFrag);
reader1 = XmlReader.Create(srXml, rs, context);

//Add the schema.
//myschema.Add("http://www.newmarketinc.com", "D:\\Documents and Settings\\Administrator\\Desktop\\MI\\DirectBook.xsd");

//Set the schema type and add the schema to the reader.
//reader.ValidationType = ValidationType.Schema;
//reader.Schemas.Add(myschema);
while (reader1.Read())
{ //empty loop;
}
Console.WriteLine("Completed validating xmlfragment");
}
catch (XmlException XmlExp)
{
Console.WriteLine(XmlExp.Message);
}
catch (XmlSchemaException XmlSchExp)
{
Console.WriteLine(XmlSchExp.Message);
}
catch (Exception GenExp)
{
Console.WriteLine(GenExp.Message);
}
finally
{
Console.Read();
}
}
public static void ShowCompileErrors(object sender, ValidationEventArgs args)
{
Console.WriteLine("Validation Error: {0}", args.Message);
}
}
}

References -
.net 1.1 - http://www.codeproject.com/cs/webservices/XmlSchemaValidator.asp,
http://support.microsoft.com/kb/318504

.net 2.0 - http://aspalliance.com/941

Cheers - Dj

No comments: