views:

76

answers:

2

Hello, i'm trying to serialize DataTable to Json or XML. is it possibly and how? any tutorials and ideas, please.

For example a have a sql table:

CREATE TABLE [dbo].[dictTable](
    [keyValue] [int] IDENTITY(1,1) NOT NULL,
    [valueValue] [int] NULL,
 CONSTRAINT [Psd2Id] PRIMARY KEY CLUSTERED 
(
    [keyValue] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

C# code:

string connectionString =
          "server=localhost;database=dbd;uid=**;pwd=**";

            SqlConnection mySqlConnection = new SqlConnection(connectionString);
            string selectString =  "SELECT keyValue, valueValue FROM dicTable";

            SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

            mySqlCommand.CommandText = selectString;

            SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();

            mySqlDataAdapter.SelectCommand = mySqlCommand;

            DataSet myDataSet = new DataSet();

            mySqlConnection.Open();

            string dataTableName = "dictionary";
            mySqlDataAdapter.Fill(myDataSet, dataTableName);

            DataTable myDataTable = myDataSet.Tables[dataTableName];
            //now how to serialize it?
+1  A: 

To XML it's simple:

DataTable myTable = new DataTable();
myTable.WriteXml(@"c:\myfile");
Carra
A: 

For DataTable to JSON Serialisation in a web environment have a look at my blog entry, that solution can also be used in regular .NET applications without the plugin architecture. Hope this helps :)

Kyryll