Steven IJzer


  • 1
Slideshow Java by WOWSlider.com v4.8

c# xml validation

This tutorial show the validation of a xml document using c#. The code uses a locally cached version of the schema file. This is done for performance reasons. Furthermore it makes shure the xml still complies with the xsd that was used when the rest of the code was created. Consider a situation where both the xml and xsd change at the online source: The result would be that the code evaluates the xml as valid and continues putting the data in a datbase e.g. The rest of the code might be expecting the old schema that is no longer compatible. If you validate against a local copy, you are warned the xml no longer complies and thus prevent database integrity errors further down the road.

The program.cs:

using System.Xml;
using System.Xml.Schema;

namespace xml_validation
{

    class Program
    {
        private static bool isValid = true;//provides tha boolean to check on.

        static void Main(string[] args)
        {
            //the cache
XmlSchemaCollection cache = new XmlSchemaCollection();
            cache.Add("urn:MyNamespace", "products.xsd");

            XmlTextReader r = new XmlTextReader("Products.xml");
            XmlValidatingReader v = new XmlValidatingReader(r);
            v.ValidationType = ValidationType.Schema;

//add the cache.            
v.Schemas.Add(cache);

            v.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler);

            while (v.Read())
            {
                // Can add code here to process the content.
            }
            v.Close();

            // Check whether the document is valid or invalid.
            if (isValid)
                Console.WriteLine("Document is valid");
            else
                Console.WriteLine("Document is invalid");
        }

        public static void MyValidationEventHandler(object sender,
                                            ValidationEventArgs args)
        {
            isValid = false;
            Console.WriteLine("Validation event\n" + args.Message);//display source of errors
        }

    }
}

Note that this allows the code to validate against a version of the schema that is cached.

The Products.xml. Typically the pointer to the schema-file here would be some online source “http://domain/products.xsd” for purpose of demonstration the xml, xsd and .exe are compiled and run from the same directory.

<?xml version="1.0"?>
<Product ProductID="123" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="urn:MyNamespace"
         xsi:schemaLocation="urn:MyNamespace products.xsd">
   <ProductName>Rugby jersey</ProductName>
</Product>

The xml schema “products.xsd” file. You would copy a cached version of this file to your program. The xsd expects a “ProductName” and “ProductID”. Make shure the namespace in the xml, xsd and code are the same. In this example “urn:MyNamespace”.

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="urn:MyNamespace"
            elementFormDefault="qualified">
   <xsd:element name="Product">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="ProductName" type="xsd:string"/>
         </xsd:sequence>
         <xsd:attribute name="ProductID" use="required" type="xsd:int"/>
      </xsd:complexType>
   </xsd:element>
</xsd:schema>