转换数据集以XML [英] Convert Dataset to XML

查看:140
本文介绍了转换数据集以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 :)

好吧,我有这个功能:

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();
}

我一直在尝试各种不同的东西,但我不断收到错误,所以我离开了怎样的DataSet转换为XML部分空白。

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.

推荐答案

您可以使用 ds.WriteXml ,但将要求你有一个来将输出到。如果你想在一个字符串输出,试试这个扩展方法:

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());
            }
        }
    }
}

用法:

var xmlString = ds.ToXml();
// OR
Response.Write(ds.ToXml());

这篇关于转换数据集以XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆