How Can write a DataSet as XML through VB.Net & C#?

XMLToday I am going to talk about XML again, today we learn how to make XML from a Dataset.

There are 3 different methods that you can chose, but before producing a XML file or XML Content we need to produce a Dataset.

[VB.Net]

  Private Sub MakeDataSet()
        Dim ds As New DataSet()
        Dim OConnString As String = "Server=CodingTips;Database=_
                                   Library;" + _
                                   "Integrated Security=true;"

        Using conn As New SqlConnection(OConnString)
            Using cmd As SqlCommand = conn.CreateCommand()

                cmd.CommandText = "SELECT * FROM Books;"
                Dim Oda As New SqlDataAdapter(cmd)
                Oda.Fill(ds)
            End Using
        End Using
    End Sub

[C#]

private void MakeDataSet()
{
    DataSet ds = new DataSet();
    string OConnString = "Server=CodingTips;Database=Library;" + _
"Integrated Security=true;";

    using (SqlConnection conn = new SqlConnection(OConnString)) {
        using (SqlCommand cmd = conn.CreateCommand()) {

            cmd.CommandText = "SELECT * FROM Books;";
            SqlDataAdapter Oda = new SqlDataAdapter(cmd);
            Oda.Fill(ds);
        }
    }
}

Now you are ready to produce XML File,follow these three different methods.
1. Write XML directly in the film

[VB.Net]

ds.WriteXml("c:/CodingTips.xml")

[C#]

ds.WriteXml("c:/CodingTips.xml")

2.The second method is GetXml , the result of this method is String but it does not support any of the advanced features of the XML serialization

[VB.Net]

Dim strxml as string = ds.GetXml()

[C#]

string strxml = ds.GetXml();

3.Sometimes you want to use all advanced features of the XML serialization but you don’t want to save the file, in this case you can use this solution.

[VB.Net]

Dim strm As New MemoryStream()
ds.WriteXml(strm)

[C#]

MemoryStream strm = new MemoryStream();
ds.WriteXml(strm);


Categories: .Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: