Create an XML schema form a DataSet

You can store the schema definition with data from a DataSet within XML file by passing XmlWriteMode.WriteSchema as the second parameter of the WriteXml method of DataSet. XmlWriteMode enumeration specifies how to write XML data and a relational schema from a DataSet.

The following code shows how generates the schema definition within the XML file

string strFileName = @"..\..\Customer.xml";

string strConnectString = "Data Source=(local);Integrated security=SSPI;Initial Catalog=AdventureWorks;";

string strText = "SELECT Top 2 * FROM Sales.Customer Order By ModifiedDate Desc";

// Create and fill a DataSet using a data adapter

SqlDataAdapter objDataAdapter = new SqlDataAdapter(strText, strConnectString);

DataSet objDataSet = new DataSet("CustomerData");

// Fill DataSet with customer record

objDataAdapter.Fill(objDataSet,"Customer");

// Write the xml schema for the DataSet

objDataSet.WriteXml(strFileName, XmlWriteMode.WriteSchema);

The resulting XML schema file contents will look like this :

<?xml version="1.0" standalone="yes"?>

<CustomerData>

<xs:schema id="CustomerData" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">

<xs:element name="CustomerData" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">

<xs:complexType>

<xs:choice minOccurs="0" maxOccurs="unbounded">

<xs:element name="Customer">

<xs:complexType>

<xs:sequence>

<xs:element name="CustomerID" type="xs:int" minOccurs="0" />

<xs:element name="TerritoryID" type="xs:int" minOccurs="0" />

<xs:element name="AccountNumber" type="xs:string" minOccurs="0" />

<xs:element name="CustomerType" type="xs:string" minOccurs="0" />

<xs:element name="rowguid" msdata:DataType="System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" type="xs:string" minOccurs="0" />

<xs:element name="ModifiedDate" type="xs:dateTime" minOccurs="0" />

</xs:sequence>

</xs:complexType>

</xs:element>

</xs:choice>

</xs:complexType>

</xs:element>

</xs:schema>

<Customer>

<CustomerID>3</CustomerID>

<TerritoryID>4</TerritoryID>

<AccountNumber>AW00000003</AccountNumber>

<CustomerType>S</CustomerType>

<rowguid>130774b1-db21-4ef3-98c8-c104bcd6ed6d</rowguid>

<ModifiedDate>2004-10-13T11:15:07.263+05:30</ModifiedDate>

</Customer>

<Customer>

<CustomerID>2</CustomerID>

<TerritoryID>1</TerritoryID>

<AccountNumber>AW00000002</AccountNumber>

<CustomerType>S</CustomerType>

<rowguid>e552f657-a9af-4a7d-a645-c429d6e02491</rowguid>

<ModifiedDate>2004-10-13T11:15:07.263+05:30</ModifiedDate>

</Customer>

</CustomerData>