- Validate XML against Schema

Here I will show you how to “Validate Xml against the provided Schema xsd”.
This is the simplest method to validate the xml from the given Schema xsd
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Data;
using System.Web;
namespace ConsoleApplication1
{
class clsValidateXml
{
public static string ErrorMessage=”";
static void validatexml()
{
//Physical path of the XML File
string XmlFilePath = @”c:\Test.xml”;
//Physical path of the XSD File
string XSDFilePath = @”c:\Test.xsd”;

XmlDocument ObjXmlDocument = new XmlDocument();
ObjXmlDocument.Load(XmlFilePath);

XmlNodeList list = null;
list = ObjXmlDocument.GetElementsByTagName(“ProductPageUrl”);
string tags = null;
foreach (XmlNode node1 in list)
{
//do something with tags
}
ObjXmlDocument.Save(@”c:\final.xml”);

try
{
// Load the schema definition
XmlReaderSettings ObjXMLSettings = new XmlReaderSettings();
ObjXMLSettings.ValidationType = ValidationType.Schema;
ObjXMLSettings.ValidationEventHandler += new ValidationEventHandler(ObjXMLSettings_ValidationEventHandler);
ObjXMLSettings.Schemas.Add(null, XmlReader.Create(XSDFilePath));

XmlNodeReader ObjXmlNodeReader = new XmlNodeReader(ObjXmlDocument);
System.Xml.XmlReader ObjXMLReader,asd = null;
ObjXMLReader = XmlReader.Create(ObjXmlNodeReader, ObjXMLSettings);

// If there XML file does not match the XSD file
//then Validation event handler is fired in this statement
while (ObjXMLReader.Read())
{
}
if (!String.IsNullOrEmpty(ErrorMessage.ToString()))
{
Console.WriteLine(ErrorMessage.ToString());
}
}

catch (XmlException ObjXMLException)
{
Console.WriteLine(“Not a Well Formed XML Document” + ObjXMLException.Message);
}
}
public static void ObjXMLSettings_ValidationEventHandler(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Error)
{
ErrorMessage+=args.Message;
}
}
public static void Main()
{
validatexml();
}
}
}

In the Next post I will Show you how to encode and decode the xml Name……

Leave a Reply