XML validation with XSD Schema without modifying XML using C #
3 answers
Easy to code multiple lines in C #.
I've created a simple command line interface utility that takes two parameters: XML, XSD and does validation.
You can download it here .
Here's the main code:
// 1- Read XML file content
reader = new XmlTextReader(XMLPath);
// 2- Read Schema file content
StreamReader SR = new StreamReader(XSDPath);
// 3- Create a new instance of XmlSchema object
XmlSchema Schema = new XmlSchema();
// 4- Set Schema object by calling XmlSchema.Read() method
Schema = XmlSchema.Read(SR,
new ValidationEventHandler(ReaderSettings_ValidationEventHandler));
// 5- Create a new instance of XmlReaderSettings object
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
// 6- Set ValidationType for XmlReaderSettings object
ReaderSettings.ValidationType = ValidationType.Schema;
// 7- Add Schema to XmlReaderSettings Schemas collection
ReaderSettings.Schemas.Add(Schema);
// 8- Add your ValidationEventHandler address to
// XmlReaderSettings ValidationEventHandler
ReaderSettings.ValidationEventHandler +=
new ValidationEventHandler(ReaderSettings_ValidationEventHandler);
// 9- Create a new instance of XmlReader object
XmlReader objXmlReader = XmlReader.Create(reader, ReaderSettings);
// 10- Read XML content in a loop
while (objXmlReader.Read())
{ /*Empty loop*/}
+3
a source to share
You can add schema to xml document
doc.Schemas.Add(schema);
And then confirm it
bool xmlvalid = true;
string lastXmlError = "";
doc.Validate(new System.Xml.Schema.ValidationEventHandler(
delegate(object sender, System.Xml.Schema.ValidationEventArgs args)
{
if (args.Severity == System.Xml.Schema.XmlSeverityType.Error)
{
xmlvalid = false;
lastXmlError = args.Message;
}
}));
if (!xmlvalid)
//raise error
+1
a source to share
Only provide a ValidationEventHandler if you want to continue validating the document beyond the first validation error. Otherwise, just do the following:
private bool ValidateDocument(string xmlFile, string xsdFile)
{
XmlReaderSettings settings = new XmlReaderSettings{ValidationType
= ValidationType.Schema};
settings.Schemas.Add(XmlSchema.Read(XmlReader.Create(xsdFile)));
XmlReader reader = XmlReader.Create(xmlFile, settings);
try
{
while(reader.Read());
return true;
}
catch (XmlException ex)
{
// XmlException indicates a validation error occurred.
return false;
}
}
The following links provide additional information:
+1
a source to share