Created
January 13, 2017 21:08
-
-
Save sachintha81/2c5fd3f159431282385f0f29ca3a4bcf to your computer and use it in GitHub Desktop.
C# Validating XML using Schemas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.