Skip to content

Instantly share code, notes, and snippets.

@sachintha81
Created January 13, 2017 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sachintha81/2c5fd3f159431282385f0f29ca3a4bcf to your computer and use it in GitHub Desktop.
Save sachintha81/2c5fd3f159431282385f0f29ca3a4bcf to your computer and use it in GitHub Desktop.
C# Validating XML using Schemas
using System;
using System.IO;
using System.Xml.Linq;
using System.Xml.Schema;
namespace XmlValidation
{
class Program
{
static void Main(string[] args)
{
string xmlFile = @""C:\TestXml.xml"";
string schemaFile = @""C:\TestXsd.xsd"";
bool isValid = false;
Exception ex = null;
if (ValidateXML(xmlFile, schemaFile, out isValid, out ex))
{
if (isValid)
Console.WriteLine(""SUCCESS"");
else
Console.WriteLine(ex.Message);
}
else
Console.WriteLine(ex.Message);
Console.ReadLine();
}
static void SchemaValidationEventHandler(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Error)
{
throw e.Exception;
}
}
static bool ValidateXML(string xmlFile, string schemaFile, out bool isValid, out Exception ex)
{
bool ret = true;
isValid = true;
ex = null;
Exception exValidate = null;
bool resultValidate = true;
try
{
XDocument xDoc = XDocument.Load(xmlFile, LoadOptions.PreserveWhitespace);
FileStream fs = new FileStream(schemaFile, FileMode.Open, FileAccess.Read);
XmlSchema schema = XmlSchema.Read(fs, SchemaValidationEventHandler);
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schema);
xDoc.Validate(schemas, (o, e) =>
{
exValidate = e.Exception;
resultValidate = false;
});
isValid = resultValidate;
ex = exValidate;
}
catch (Exception e)
{
ex = e;
ret = false;
}
return ret;
}
}
}
@sachintha81
Copy link
Author

Note:

To create the schema, import the XML file into Visual Studio, open it, go to menu item XML and select ""Create Schema"".

Might need to change stuff like maxOccurs, minOccurs according to your needs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment