Thursday, 23 October 2008

Validating an XML file against its Schema (XSD)

string strXmlFile;
string strXsdFile;
XmlDocument xmlDoc = null;
// Retrieve XML and XSD files from the locations specified in the Settings file.
strXmlFile = Properties.Settings.Default.XMLLocation;
strXsdFile = Properties.Settings.Default.XSDLocation;
    // Load XML data into a new XMLDocument
    xmlDoc = new XmlDocument();
    // Validate the XML document against the Schema.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add("", strXsdFile);
    XmlReader objXmlReader = XmlReader.Create(strXmlFile, settings);
    while (objXmlReader.Read()) { }
catch (XmlSchemaValidationException XmlSchemaEx)
    //"Xml file didn't conform to the schema.";
catch (XmlException XmlEx)
    //"Invalid XML File Location.";

Note: The namespace with the schema's 'Add' Function must match the schema namespace in the file. In this instance (

No comments: