Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Dataset to XML

I've been stuck with this problem for a few hours and can't seem to figure it out, so I'm asking here :)

Alright, I've got this function:

private void XmlDump()
{
    XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
    XElement rootElement = new XElement("dump");
    rootElement.Add(TableToX("Support"));

    string connectionString = ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString;
    SqlConnection con = new SqlConnection(connectionString);
    string sql = "select * from support";
    SqlDataAdapter da = new SqlDataAdapter(sql, con);

    DataSet ds = new DataSet("Test");
    da.Fill(ds, "support");

    // Convert dataset to XML here

    var docresult = // Converted XML

    Response.Write(docResult);
    Response.ContentType = "text/xml; charset=utf-8";
    Response.AddHeader("Content-Disposition", "attachment; filename=test.xml");
    Response.End();
}

I've been trying all kind of different things but I keep getting errors, so I've left the how to convert DataSet to XML part blank.

And another thing, this query contains columns with special characters.

like image 412
NomenNescio Avatar asked Dec 05 '11 10:12

NomenNescio


2 Answers

You can use ds.WriteXml, but that will require you to have a Stream to put the output into. If you want the output in a string, try this extension method:

public static class Extensions
{
    public static string ToXml(this DataSet ds)
    {
        using (var memoryStream = new MemoryStream())
        {
            using (TextWriter streamWriter = new StreamWriter(memoryStream))
            {
                var xmlSerializer = new XmlSerializer(typeof(DataSet));
                xmlSerializer.Serialize(streamWriter, ds);
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
        }
    }
}

USAGE:

var xmlString = ds.ToXml();
// OR
Response.Write(ds.ToXml());
like image 104
Abdul Munim Avatar answered Sep 19 '22 23:09

Abdul Munim


Simply use Dataset.getXml():

doc.LoadXml(ds.GetXml());
like image 32
Venkat Avatar answered Sep 18 '22 23:09

Venkat