Spot the web RSS 2.0
# Monday, December 29, 2008

XML documents can reference optional documents that specify how the XML documents should be structured. These optional documents called Documents Type Definitions (DTDs) and Schemas.

There are two kinds of definition for schemas currently:

1. Microsoft XML Schema
It uses the extension .xdr (XML-Data Reduced) you can check the attached files for the this Schema syntax, it is an xml document, but has special elements and attributes.
2. W3C XML Schema
It uses the extension .xsd (XML Schema Definitions) also it is an XML Document with special elements.

The second approach, XSD Schema, has been supported by Microsoft .NET Framework and is the best approach for .NET developers.  Schema files are a special kind of XML file that define the structure of an XML file via some pre-defined elements and attributes.

Using this Schema file you can validate your XML file to make sure it fits to your application's needs and validate the inputs in order to prevent any exception in your code. 

The .Net framework gives you all the tools you need so that you can build XSD schemas and also validate them.

First, let's see how can we create a schema using XSD.exe file (It comes with Visual Studio):

The XML Schema Definition tool generates XML schema or common language runtime classes from XDR, XML, and XSD files, or from classes in a runtime assembly.

The following command generates an XML schema from myFile.xml and saves it to the specified directory

xsd myFile.xml /outputdir:myOutputDir

Consider that we have the following xml data file EmployeeList.xml:

<EmployeeList>
<Company ID="1">
<Employee>Employee11Employee>
<Employee>Employee12Employee>
<Employee>Employee13Employee>
Company>
<Company ID="2">
<Employee>Employee21Employee>
<Employee>Employee22Employee>
<Employee>Employee23Employee>
Company>
<Company ID="3">
<Employee>Employee31Employee>
<Employee>Employee32Employee>
<Employee>Employee33Employee>
<Employee>Employee34Employee>
Company>
EmployeeList>

Now, execute XSD.exe on the xml data file:

> XSD EmployeeList.xml

The result xsd file EmployeeList.xsd will be :

xml version="1.0" encoding="utf-8"?>
<xs:schema id="EmployeeList" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="EmployeeList" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Company">
<xs:complexType>
<xs:sequence>
<xs:element name="Employee" nillable="true" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:simpleContent msdata:ColumnName="Employee_Text" msdata:Ordinal="0">
<xs:extension base="xs:string">
xs:extension>
xs:simpleContent>
xs:complexType>
xs:element>
xs:sequence>
<xs:attribute name="ID" type="xs:string" />
xs:complexType>
xs:element>
xs:choice>
xs:complexType>
xs:element>
xs:schema>

Second, now that we have our Schema let's see the steps that we need to do in order to validate against our schema (.NET 2.0):

1.      Read the XML file content as Stream, TextReader or XmlReader.

2.      Read the Schema file content as Stream, TextReader or XmlReader.

3.      Create a new instance of XmlSchema object.

4.      Set XmlSchema object by calling XmlSchema.Read() method and passing the content of Schema file
     and ValidationEventHandler method address to it.

5.      Create a new instance of XmlReaderSettings object.

6.      Set ValidationType for XmlReaderSettings object to Schema.

7.      Add your XmlSchema object to XmlReaderSettings Schemas collection by calling its Schemas.Add() method.

8.      Add your ValidationEventHandler method address to XmlValidationReader's ValidationEventHandler handler.

9.      Create a new instance of XmlReader object and pass your XML file content (as Stream or a Reader object)
     and XmlReaderSettings object to it.

10.  Call Read() method of the Reader or Stream object to contain your XML file content in a loop to parse
     and validate it completely.

11.  Add your logic to ValidationEventHandler method you created to implement what you want to be done in
     the validation process.


Here is the code to accomplish this:

private void ValidatingProcess(string XSDPath, string XMLPath)
{
    try
    {
        // 1- Read XML file content
        this.Reader = new XmlTextReader(XMLPath);
 
        // 2- Read Schema file content
        StreamReader SR = new StreamReader(XSDPath);
 
        // 3- Create a new instance of XmlSchema object
        XmlSchema Schema = new XmlSchema();
        // 4- Set Schema object by calling XmlSchema.Read() method
        Schema = XmlSchema.Read(SR, 
            new ValidationEventHandler(ReaderSettings_ValidationEventHandler)); 
 
        // 5- Create a new instance of XmlReaderSettings object
        XmlReaderSettings ReaderSettings = new XmlReaderSettings();    
        // 6- Set ValidationType for XmlReaderSettings object
        ReaderSettings.ValidationType = ValidationType.Schema;                
        // 7- Add Schema to XmlReaderSettings Schemas collection
        ReaderSettings.Schemas.Add(Schema); 
 
        // 8- Add your ValidationEventHandler address to
        // XmlReaderSettings ValidationEventHandler
        ReaderSettings.ValidationEventHandler +=
            new ValidationEventHandler(ReaderSettings_ValidationEventHandler);
 
        // 9- Create a new instance of XmlReader object
        XmlReader objXmlReader = XmlReader.Create(Reader, ReaderSettings);
 
 
        // 10- Read XML content in a loop
        while (objXmlReader.Read())
        { /*Empty loop*/
 
    }//try
    // Handle exceptions if you want
    catch (UnauthorizedAccessException AccessEx)
    {
        throw AccessEx;
    }//catch
    catch (Exception Ex)
    {
        throw Ex;
    }//catch
}
 
private void ReaderSettings_ValidationEventHandler(object sender, 
    ValidationEventArgs args)
{
    // 11- Implement your logic for each validation iteration
    string strTemp;
    strTemp = "Line: " + this.Reader.LineNumber + " - Position: " 
        + this.Reader.LinePosition + " - " + args.Message; 
 
    this.Results.Add(strTemp);
}

Monday, December 29, 2008 1:30:46 PM (Jerusalem Standard Time, UTC+02:00)  #    Comments [1] - Trackback
.Net | C# | Serialization | Visual Studio | XML | XSD
# Wednesday, November 28, 2007

First let's go over the basics:

By default, an XML element name is determined by the class or member name. In a simple class named Book, a field named Author will produce an XML element tag <Author>, as shown here:

public class Book
{
    public string Author;
}

When an instance of the Book class is serialized, it might produce this XML:
....
<Author>John Doe</Author>
....

Now, here are some of the elements we can use to control the serialization:

[DefaultValueAttribute(0)]
Can only be applied to numeric members (int, float, double), when no value is given it will put the default value 0. It is very important to remember that if the value of this member will be 0 (or equals to the default value) this member will not be serialized!

public class Book
{
    public string Author;
    [DefaultValueAttribute(0)]
    public int BookNum;
}

In the XSD Schema it will do this:
<xs:element minOccurs="0" maxOccurs="1" default="0" name="BookNum" type="xs:int" />

 

[XmlElement(ElementName = "Book_Number")]
With this attribute you can specify the element name instead of using the member name.

public class Book
{
    public string Author;
      [DefaultValueAttribute(0)]
      [XmlElement(ElementName = "Book_Number")]

    public int BookNum;
}

In the XSD Schema it will do this:
<xs:element minOccurs="0" maxOccurs="1" default="0" name="
Book_Number" type="xs:int" />

Will be continued in Part 2...

Wednesday, November 28, 2007 9:30:33 AM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
Schema | Serialization | XML | XSD
Navigation
Archive
<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Guy Levin
Sign In
Statistics
Total Posts: 63
This Year: 0
This Month: 0
This Week: 0
Comments: 14
Themes
All Content © 2010, Guy Levin