Convert Dataset to XML

前端 未结 7 1745
野性不改
野性不改 2020-11-30 05:14

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         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 05:36

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

提交回复
热议问题