DataTable.ReadXmlSchema Method (XmlReader)
Assembly: System.Data (in System.Data.dll)
Use the ReadXmlSchema method to create the schema for a DataTable. The schema includes table, relation, and constraint definitions.
To write a schema to an XML document, use the WriteXmlSchema method.
The XML schema is interpreted according to the XSD standard.
Data corruption can occur if the msdata:DataType and the xs:type types do not match. No exception will be thrown.
The ReadXmlSchema method is generally invoked before invoking the ReadXml method which is used to fill the DataTable.
Note |
|---|
The way to create a nested relation using XML schema is to have implicit nested elements. Additionally, the nested relation could be re-wired, to use explicit column names. It is mandatory for elements to be implicitly nested for the corresponding DataTables to participate in a nested relation. |
The following console application creates a new DataTable, and writes the schema for that table to a MemoryStream. Then, the example creates a new DataTable and reads its schema from the saved XML schema, using a XmlTextReader (which inherits from XmlReader) as its source.
private static void DemonstrateReadWriteXMLSchemaWithReader() { DataTable table = CreateTestTable("XmlDemo"); PrintSchema(table, "Original table"); // Write the schema to XML in a memory stream. System.IO.MemoryStream xmlStream = new System.IO.MemoryStream(); table.WriteXmlSchema(xmlStream); // Rewind the memory stream. xmlStream.Position = 0; DataTable newTable = new DataTable(); System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(xmlStream); newTable.ReadXmlSchema(reader); // Print out values in the table. PrintSchema(newTable, "New table"); } private static DataTable CreateTestTable(string tableName) { // Create a test DataTable with two columns and a few rows. DataTable table = new DataTable(tableName); DataColumn column = new DataColumn("id", typeof(System.Int32)); column.AutoIncrement = true; table.Columns.Add(column); column = new DataColumn("item", typeof(System.String)); table.Columns.Add(column); // Add ten rows. DataRow row; for (int i = 0; i <= 9; i++) { row = table.NewRow(); row["item"] = "item " + i; table.Rows.Add(row); } table.AcceptChanges(); return table; } private static void PrintSchema(DataTable table, string label) { // Display the schema of the supplied DataTable: Console.WriteLine(label); foreach (DataColumn column in table.Columns) { Console.WriteLine("\t{0}: {1}", column.ColumnName, column.DataType.Name); } Console.WriteLine(); }
Available since 2.0
