Validating XML documents against Schemas PDF Print E-mail
User Rating: / 0
PoorBest 
Tuesday, 10 March 2009
HTML clipboard

About XmlSchema Class

Contains the definition of a schema. All XML Schema definition language (XSD) elements are children of the schema ReadTargetNamespaceTargetNamepace is used to Get or set the property for the schema target namespace. The URI reference of the namespace of this schema. We use Method Read to be able to get the TargetNamepace property, or Get an XmlSchema reference to be added to XmlSchemaCollection, you'll see how later on this tutroial

Example 2:
element. Represents the World Wide Web Consortium (W3C) schema element. In this Class we will use the Method and the Property

//1st Param: xReader is an XmlReader object in Example 1//2nd Param: 
SchemaReadError is Method that Implements ValidationEventHandler event
//2nd Param is The validation event handler that receives information about the XML
  //Schema syntax errors.  new ValidationEventHandler(SchemaReadError));
XmlSchema xmlSchema = XmlSchema.Read(xReader,

Note: XmlSchema Class can be used for XSD Only not XDR.

About XmlSchemaCollection:

From its name, it is a Colletion of Schemas that will be used to validate the XML Documents, this class has Add Method which will be used to add the schemas to collection, this Method is over loaded, in this tutorial we are using 2 of those overloaded, we'll see that later.

Example 3:

XmlSchemaCollection m_schSchemas = new XmlSchemaCollection();
m_schSchemas.Add(xmlSchema); //xmlSchema in Example 2
//namespace: I'll use the file name as the name space for xdr filesstring namespace,
 string URI_or_filePath); 
// will shown later..
m_schSchemas.Add(

About XmlValidatingReader:

Represents a reader that provides DTD, XML-Data Reduced (XDR) schema, and XML Schema definition language (XSD) schema validation.

This is used to validate the XML Document, we will perform the validation node by node according to the defined schema in the XML Document. The Constructor of this Class takes XmlReader as parameter so we'll pass the XmlTextReader object to this constructor. This Class also has Schemas Property which is used to assign the XmlSchemaCollection to use for validation.

Also there is a property called ValidationType it is an enum type which has 5 posible values Auto,None,Schema,DTD & XDR, I'll use Auto which will make XmlValidatingReader validates if DTD or schema information is found. This property must be set before the first call to Read Method or InvalidOperationException will be thrown.

Also don't forget to set the ValidationEventHandler event of the XmlValidatingReader object.

Program describtion:

First we will load the XML document we want to work on in a combo box, and the Validation documents will be loaded in an XmlSchemaCollection.

we choose the XML document from the Combo box then click on validate and the document will be validated Automaticly as we set the ValidationType property to Auto, the results will be displayed in a text box.

Code:

//Member Fields
private string[] m_strXmlFiles; //Hold the XML Files Path

private XmlSchemaCollection m_schSchemas; //Schema Collection for Validation files

private bool m_bValid; //Validation result

//Constructor
public frmXmlValidation()
{
    InitializeComponent();
    m_schSchemas = new XmlSchemaCollection(); //Create new Collection
    m_bValid = true; // Assume document is valid
}

//Loading XML files
private void btnLoadXml_Click(object sender, System.EventArgs e)
{
    //dlgFileChooser is OpenFileDialog, here we initilaize its property
    dlgFileChooser.Filter = "Xml Files | *.xml";//only .xml files will be shown
    dlgFileChooser.Multiselect = true; // can select more than one file
    dlgFileChooser.Title = "Load Xml Files";
               
    DialogResult Results = dlgFileChooser.ShowDialog();

    if(Results == DialogResult.Cancel)
        return;

    cmbXmlFiles.Items.Clear();
    m_strXmlFiles = dlgFileChooser.FileNames; // store file names in an array
    string[] FileNames = dlgFileChooser.FileNames; // store file names in Temp array

    //Extract file name from the the File Path, just want to display file name in the Combo box
    //not the whole Path
    for(int i=0; i{
        string strItem = dlgFileChooser.FileNames[i];
        int intIndex = strItem.LastIndexOf("\\");
        FileNames[i] = strItem.Substring(intIndex+1);
    }
    //add the Array to the combo box
    cmbXmlFiles.Items.AddRange(FileNames);
}

//Loading the Schemas
private void btnLoadValidationFiles_Click(object sender, System.EventArgs e)
{
    //Open file Dialog Initialization
    //Show only XSD & XDR Files
    dlgFileChooser.Filter = "XDR Files | *.xdr| XSD Files | *.xsd|Both |*.xsd;*.xdr";
    dlgFileChooser.Multiselect = true;
    dlgFileChooser.Title = "Load Xml Validation Files [XDR & XSD Files]";
    dlgFileChooser.FilterIndex = 3;

        DialogResult Results = dlgFileChooser.ShowDialog();
    if(Results == DialogResult.Cancel)
        return;

    //Loop throw the FileNames to check for XSD files
    for(int i=0; i{
        int len = dlgFileChooser.FileNames[i].Length;
        //Test foe XSD Files
        if(dlgFileChooser.FileNames[i].Substring(len-3).Equals("xsd"))
        {
            //Load XML Doc in XmlTextReader
            XmlTextReader xReader = new XmlTextReader(dlgFileChooser.FileNames[i]);
            try
            {           
                XmlSchema xmlSchema = XmlSchema.Read(xReader,
                                         new ValidationEventHandler(SchemaReadError));
                m_schSchemas.Add(xmlSchema);
                //if you are going to use the other overloaded Method
                //which take the 1st Param as namespace,
                //this will typically be the targetNamespace property like this:
                //m_schSchemas.Add(xmlSchema.TargetNamespace,dlgFileChooser.FileNames[i])
            }
            catch(XmlException err)
            {
                MessageBox.Show(err.Message+ " in " + Environment.NewLine +
                                dlgFileChooser.FileNames[i],
                               "Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            finally
            {
                if(xReader != null)
                    xReader.Close();
            }
        }
        else
        {
            //Loading the Xdr Files
            //Set the URI to be the file name
            string strFileName = dlgFileChooser.FileNames[i];
            int intSlashIndex = strFileName.LastIndexOf('\\');
            //CString is my defined Class add as a dll reference
            //you can check for its tutorial on:
            //http://www.csharpfriends.com/Members/Main/Tutorials/get_tutorial.aspx?tutID=85
            strFileName = CString.Right(strFileName, len - intSlashIndex-1);
            m_schSchemas.Add(strFileName,dlgFileChooser.FileNames[i]);
        }
    }
}

//Perform Validation Test
private void btnValidate_Click(object sender, System.EventArgs e)
{
               
    int intFileIndex = cmbXmlFiles.SelectedIndex;
    //Check for Combo Selection
    if(intFileIndex == -1)
    {
        MessageBox.Show("Please Load XML Files","Note",
                            MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
        return;
    }
    //check for Schemas if they are loaded
    if(m_schSchemas.Count == 0)
    {
        MessageBox.Show("Please Load Validation Files",
                                "Note",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
        return;
    }

    XmlTextReader xReader;
    string strFileName;
    strFileName = m_strXmlFiles[intFileIndex]; //get XML Document Path by the Selcetion index
    xReader = new XmlTextReader(strFileName); //load the selected XML Document

    //Get Validator
    XmlValidatingReader xValidator = new XmlValidatingReader(xReader);

    //Assign Schemas to the XmlValidatingReader object
    xValidator.Schemas.Add(m_schSchemas);

    xValidator.ValidationType = ValidationType.Auto; //set the ValidationType

    //Set the Event Handler for ValidationEventHandler
    //These events occur during Read and only if a ValidationType of DTD, XDR, Schema, 
    //or Auto is specified.
    //If no event handler is provided an XmlException is thrown on the first validation error 
    xValidator.ValidationEventHandler += new ValidationEventHandler(ValidationError);

    //Validate Document Node By Node
    while(xValidator.Read()) ; //empty body

    //Check for Validation Results
    if(m_bValid)
        txtOutput.Text =cmbXmlFiles.SelectedItem.ToString() + " is valid document";

    m_bValid = true; //reset variable

    xValidator.Close();
}

//ValidationEventHandler Call-back Method
private void ValidationError(object sender, ValidationEventArgs arguments)
{
    txtOutput.Text = arguments.Message; // Display error
    m_bValid = false; //validation failed
}

Last Updated ( Tuesday, 10 March 2009 )
 
< Prev   Next >
School Joomla Templates and Joomla Tutorials