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, December 24, 2008

Don't use your web methods to return strings as most programmers do, use them to return true XMLs.


instead of using this:

[WebMethod]
public string MyLameWebMethod()
{
XmlDocument dom = new XmlDocument();
// load XML Data ...
return dom.OuterXml;
}

Now when we want to read it on the client side we want the XML and then the operation is:
XML -> String -> XML


Use this:

[WebMethod]
public XmlDocument MyBetterWebMethod()
{
XmlDocument dom = new XmlDocument();
// load some XML ...
return dom;
}

Here we are skipping over the String step and using much more valid XML document.


Now you are avoiding an added level of transferring your XML document to string and then back to XML.
Wednesday, December 24, 2008 12:01:38 PM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
.Net | C# | XML
# Tuesday, March 18, 2008

Google updated their charts API, which they first released back in December 2007. First of all, the old limit of 50,000 queries per user per day has been removed (though Google asks you email them if you receive more than 250,000 queries a day so they can better scale this).

Also, there are several extended or new features. Among them are radar charts, sparklines, and maps. The last one is perhaps the most interesting, as it lets you display and color a map. While you can already use the Google Maps API for certain needs, this is a much more minimalist map that might come in handy for illustrations, games, traffic visualization and other things. As usual, generating maps or any other chart type consists of simply formulating a special URL.

Tuesday, March 18, 2008 9:08:39 AM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
Google | Web 2.0
Navigation
Archive
<August 2016>
SunMonTueWedThuFriSat
31123456
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 2016
Guy Levin
Sign In
Statistics
Total Posts: 63
This Year: 0
This Month: 0
This Week: 0
Comments: 14
Themes
All Content © 2016, Guy Levin