Home   |   QuickStart Welcome   |   ASP.NET   |   Web Services   |   How Do I...?   
  |   I want my samples in...      

How Do I...? Common Tasks QuickStart Tutorial

How Do I...Load a DataSet with XML?

This sample illustrates how to load a DataSet with XML Data. The sample builds on the topic, How Do I...Create DataSet mappings from an XSD schema?, by first loading XML data into an XmlDataDocument and then accessing this data from the DataSet. The DataSet has previously loaded a schema in order to create the internal mappings. This sample in effect shows the transition between XML data and the creation of relational objects to access that XML data.

VB LoadDataSetXMLData.aspx
Run Sample View Source

As shown in the following code, this sample implements the ParseSchema function to load the XML Schema Definition language (XSD) schema, books.xsd, into the DataSet property on the XmlDataDocument. Then, the sample uses the Load method of the XmlDataDocument to load the XML file, books.xml.

		
private const String document = "books.xml";
private const String myLoadSchema = "books.xsd";
private XmlDataDocument myXmlDataDocument;

public static void Main()
{
    String[] args = {document, myLoadSchema};
    LoadDataSetXMLDataSample myLoadDataSetXMLDataSample = new LoadDataSetXMLDataSample();
    myLoadDataSetXMLDataSample.Run(args);
}

public void Run(String[] args)
{
    try
    {
        Console.WriteLine("Creating an XmlDataDocument ...");
        myXmlDataDocument = new XmlDataDocument();
        ParseSchema(args[1]);
        DisplayTableStructure();

        myXmlDataDocument.Load(args[0]);

        DisplayTables(myXmlDataDocument.DataSet);
    }
    catch (Exception e)
    {
        Console.WriteLine ("Exception: {0}", e.ToString());
    }
}

// Loads a specified schema into the DataSet
public void ParseSchema(String schema)
{
    StreamReader myStreamReader = null;

    try
    {
        Console.WriteLine("Reading Schema file ...");
        myStreamReader = new StreamReader(schema);
        myXmlDataDocument.DataSet.ReadXmlSchema(myStreamReader);
    }
    catch (Exception e)
    {
        Console.WriteLine ("Exception: {0}", e.ToString());
    }
    finally
    {
        if (myStreamReader != null)
            myStreamReader.Close();
    }
}
C#

As in How Do I...Create DataSet Mappings from an XSD schema?, the DisplayTableStructure method (built with the books.xsd schema file) enables the sample to display the internal table structure by simply iterating over the collections of Tables, Columns, and Rows, and then formatting the output. This sample extends this concept with the DisplayTables method (shown in the following code) which enables the sample to display the contents of the XML file. This sample uses the For Each keyword instead of a For loop to illustrate an alternative mechanism for iterating over the collections.

		
// Displays the contents of the DataSet tables
private void DisplayTables(DataSet dataset)
{
    // Navigate Dataset
    Console.WriteLine("Content of Tables ...\r\n");

    foreach(DataTable table in dataset.Tables)
    {
        Console.WriteLine("TableName = " + table.TableName);
        Console.WriteLine ("{0}", "---------");
        Console.WriteLine("Columns ...\r\n");

        foreach(DataColumn column in table.Columns)
        {
            Console.Write("{0,-22}",column.ColumnName);
        }
        Console.WriteLine();
        Console.WriteLine("\r\nNumber of rows = {0}", table.Rows.Count.ToString());
        Console.WriteLine("Rows ...\r\n");

        foreach(DataRow row in table.Rows)
        {
            foreach(Object value in row.ItemArray)
            {
                Console.Write("{0,-22}",value.ToString());
            }
            Console.WriteLine();
        }
        Console.WriteLine();
    }
}
C#

The following output shows the table names, column names, and row contents of books.xml as displayed by the DisplayTables method.

Creating an XmlDataDocument ...
Reading Schema file ...

Table structure

Tables count=3
	TableName='bookstore'.
	Columns count=1
		ColumnName='bookstore_Id', type = System.Int32
	TableName='book'.
	Columns count=5
		ColumnName='title', type = System.String
		ColumnName='price', type = System.Decimal
		ColumnName='genre', type = System.String
		ColumnName='book_Id', type = System.Int32
		ColumnName='bookstore_Id', type = System.Int32
	TableName='author'.
	Columns count=3
		ColumnName='first-name', type = System.String
		ColumnName='last-name', type = System.String
		ColumnName='book_Id', type = System.Int32
Content of Tables ...

TableName = bookstore
---------
Columns ...

bookstore_Id

Number of rows = 1
Rows ...

0

TableName = book
---------
Columns ...

title                 price                 genre                 book_Id               bookstore_Id

Number of rows = 3
Rows ...

The Autobiography of Benjamin Franklin8.99                  autobiography         0                     0
The Confidence Man    11.99                 novel                 1                     0
The Gorgias           9.99                  philosophy            2                     0

TableName = author
---------
Columns ...

first-name            last-name             book_Id

Number of rows = 3
Rows ...

Benjamin              Franklin              0
Herman                Melville              1
Sidas                 Plato                 2

Summary

  1. XML data that has been loaded into an XmlDataDocument can be accessed via the relational methods on the DataSet property.
  2. XML data can also be read when relational data has been entered through the DataSet property of XmlDataDocument.



Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2004 Microsoft Corporation. All rights reserved.