Monday, 15 October 2012

XML From A Dataset(sql server) To display as XML

Displaying XML from a dataset in this case SQL Server is pretty straight forward.

This is useful if you want to make a call to a page with parameters you may want to pass.

You will need using System.Data.SqlClient; in your class for this.

Heres a quick example:
string connStr = "Data Source=localhost;Initial Catalog=YourDatabase;Integrated Security=True";

            using (SqlConnection conn = new SqlConnection(connStr))
            {
                SqlCommand command = new SqlCommand("select * from test", conn);
                conn.Open();
                DataSet ds = new DataSet();
                ds.DataSetName = "YourDataset";
                ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, "Item");
                Response.ContentType = "text/xml";
                ds.WriteXml(Response.OutputStream);
            }

Remember you could use the sql helper DAL instead of the method above to retrieve the dataset.

No comments: