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;
 
 
try
{
    // Load XML data into a new XMLDocument
    xmlDoc = new XmlDocument();
    xmlDoc.Load(strXmlFile);
 
    // Validate the XML document against the Schema.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
 
    settings.Schemas.Add("http://www.w3.org/2001/Messages.xsd", 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 (http://www.w3.org/2001/Messages.xsd).

No comments: