9.2. Using XSD Schema Files to Save and Load a DataSet Structure
Problem
You need to create an XSD schema from a DataSet
or DataTable
and to define the schema of a DataSet
or DataTable
from an XSD schema.
Solution
Use the XmlTextWriter
and XmlTextReader
classes together with the WriteXmlSchema()
and ReadXmlSchema()
methods of the DataSet
and DataTable
classes.
The solution creates a DataSet
containing the schema and data for the Sales.SalesOrderHeader
and Sales.SalesOrderDetail
tables in AdventureWorks
. A data relation for the tables is created in the DataSet
. The XML schema for the DataSet
is written to a file named Schema.xsd in the same directory as the solution file LoadSaveDataSetXsdSchema.sln. Next, the solution creates a DataSet
and reads in schema from the XML file Schema.xsd. Finally, metadata about the DataSet
schema are written to the console.
The C# code in Program.cs in the project LoadSaveDataSetXsdSchema
is shown in Example 9-3.
Example 9-3. File: Program.cs for LoadSaveDataSetXsdSchema solution
using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Xml; using System.Text; namespace LoadSaveDataSetXsdSchema { class Program { private const string fileName = @"..\..\..\Schema.xsd"; static void Main(string[] args) { string sqlConnectString = "Data Source=(local);" + "Integrated security=SSPI;Initial Catalog=AdventureWorks;"; string sqlSelect = "SELECT * FROM Sales.SalesOrderHeader;" + "SELECT * FROM Sales.SalesOrderDetail"; DataSet dsSource ...
Get ADO.NET 3.5 Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.