Wednesday 29 October 2008

C# - Generating Strong Typed Datasets


Over the past few weeks I have been working with Strong Typed Datasets in C# to parse XML content easily and more efficiently.

If you've ever had an Xml file and struggled to flawlessly parse it without errors, and write it back (using System.Xml namespace objects like: XMLReader or XmlDocument) then you should take a look at Strong typed Datasets.

If you've worked with Datasets, then this should come naturally. The idea is, once the XML content has been parsed into the Dataset, we can access the data through column and row information within the Dataset.

Heres how we go about it...

1. Find the "xsd.exe" tool. This is shipped with all versions of Visual Studio or can be downloaded from Microsoft's download center. This will allow us to create an XSD and .cs file for our Xml File.
2. Ensure your Xml File is valid Xml.
3. Use the xsd.exe tool to create the XSD and .cs from your xml by command line.

xsd.exe .xml - This will generate the schema (XSD) based on the XML File.
xsd.exe .xsd /d - This will generate the .cs based on the schema (XSD).


Heres a batch script to automate this process...

@echo off
 
:BEGIN
 
CLS
 
COLOR A
 
REM --- Get XML file name.
echo "What is the Path/Name of the XML file (excluding '.xml'): "
set /p XMlFile=
echo.
echo.
echo "Generating XSD Schema Definitions..."
xsd.exe %XMlFile%.xml
echo.
echo.
echo "Generating Strongly Typed DataSet file..."
xsd.exe %XMlFile%.xsd /d
echo.
echo.
echo "Strongly Typed DataSet Created Successfully!"
echo.
 
PAUSE


4. Add these 3 files to your C# project. You will notice the class name in the .cs file derives its name from the main tag within your xml. Don't forget to add the namepsace if applicable!
If you have done this corrently, you will notice the class inherits the DataSet class: "global::System.Data.DataSet" .

5. Create a new instance of the class, then call the "ReadXml()" method, specifiying the path to the XML file as a string. This will parse your XML file and popualte the Dataset. As the class was generated from the XSD, the template should match up!

6. You may also note that the instance you've created in step (5) contains accessors (one for each child note of your xml!)... Each of these has a "Rows" accessor, which will return a DataRowCollection object. If we run a loop on this collection, we will be able to extract the information!


If the "ReadXml()" function fails, you may need to re-structure your XML. The erros are quite self-explanatory, but generally this will fail due to an XML parser error.

Sean

No comments: