Simple XML Schema Definition snippet

It is amazing how things get clearer when you actually try them out.

 

For example, write by hand a XSD for the following simple XML document:

 

<?xml version="1.0" encoding='ISO-8859-1' ?>

<wn:root xmlns:wn="wn-uniqueurl">

      <wn:item info="item1"/>

      <wn:item info="item2"/>

      <wn:item info="item3"/>

</wn:root>

 

An option is:

 

<?xml version="1.0" encoding='ISO-8859-1' ?>

<s:schema

  xmlns:s='https://www.w3.org/2001/XMLSchema'

  targetNamespace='wn-uniqueurl'

  xmlns='wn-uniqueurl'

  elementFormDefault='qualified'

  attributeFormDefault='unqualified'>

     

 <s:element name='root' type='rootType' />

 <s:complexType name='rootType'>

  <s:sequence>

   <s:element name='item' type='itemType' maxOccurs="unbounded"/>

  </s:sequence>

 </s:complexType>

 <s:complexType name='itemType'>

  <s:attribute name='info' type='s:string' />

 </s:complexType>

</s:schema>

 

The following code reports XSD validation messages:

 

using System;

using System.Xml;

using System.Xml.Schema;

using w=System.Console;

class exe

{

 static void OnXSDError(object sender, ValidationEventArgs args)

 {

  w.WriteLine("XSD {0}:{1}",args.Severity,args.Message);

 }

 static void Main(string[] args)

 {

  try

  {

   string xml=args[0];

   string xsd=args.Length==2? args[1] : string.Empty;

   XmlValidatingReader reader=null;

   try

   {

    reader=new XmlValidatingReader(new XmlTextReader(xml));

    reader.ValidationType=ValidationType.Schema;

    reader.ValidationEventHandler +=new ValidationEventHandler(OnXSDError);

    if(xsd!=string.Empty) reader.Schemas.Add(null,xsd);

    while(reader.Read()){}

    w.WriteLine("Schema validation done");

   }

   finally

   {

    reader.Close();

   }

  }

  catch(Exception err)

  {

   w.WriteLine(err.Message);

   if( err.InnerException!=null)

   {

    w.WriteLine(err.InnerException.Message);

   }

  }

 }

}