When handling XML files you are going to need to validate the XML, and the best way, currently, is to use an XSD Schema. It took me a little while to work out how to do this, and with help from Assaf Lavie I finally came up with a method to validate two streams, one holding the XML the other the XSD.
public void Validate(Stream xml, Stream xsd)
{
if (xml == null)
{
throw new ArgumentNullException(“xml”);
}
if (xsd == null)
{
throw new ArgumentNullException(“xsd”);
}
xml.Seek(0, SeekOrigin.Begin);
var readerXML = new StreamReader(xml);
string textXML = readerXML.ReadToEnd();
if (string.IsNullOrEmpty(textXML))
{
throw new ArgumentNullException(“xml need to hold some information”);
}
xsd.Seek(0, SeekOrigin.Begin);
var readerXSD = new StreamReader(xsd);
string textXSD = readerXSD.ReadToEnd();
if (string.IsNullOrEmpty(textXSD))
{
throw new ArgumentNullException(“xsd need to hold some information”);
}
try
{
// 1- Set the streams to the beginning
xml.Seek(0, SeekOrigin.Begin);
xsd.Seek(0, SeekOrigin.Begin);
var errorMessages = new List<string>();
// 2- Read XML file content
var xmlReader = new XmlTextReader(xml);
// 3- Read Schema file content
StreamReader schemaReader = new StreamReader(xsd);
// 4- Set Schema object by calling XmlSchema.Read() method
XmlSchema Schema = XmlSchema.Read(schemaReader, (o, e) =>
{
errorMessages.Add(e.Message);
});
// 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 += (o, e) =>
{
errorMessages.Add(e.Message);
};
// 9- Create a new instance of XmlReader object
XmlReader objXmlReader = XmlReader.Create(xmlReader, readerSettings);
// 10- Read XML content in a loop
while (objXmlReader.Read())
{ /*Empty loop*/}
// 11- Raise exception, if XML validation fails
if (errorMessages.Count() > 0)
{
throw new Exception(string.Join(“\r\n”, errorMessages.ToArray()));
}
}
catch (XmlException XmlExp)
{
throw new XMLValidationException(XmlExp.Message, XmlExp);
}
catch (XmlSchemaException XmlSchExp)
{
throw new XMLValidationException(XmlSchExp.Message, XmlSchExp);
}
catch (Exception GenExp)
{
throw;
}
finally
{
xml.Seek(0, SeekOrigin.Begin);
xsd.Seek(0, SeekOrigin.Begin);
}
}