DataContractSerializer - how can I output the xml to a string (as opposed to a file)

蓝咒 提交于 2019-12-02 17:26:26

Something like this - put your output into a MemoryStream and then read that back in:

public static string DataContractSerializeObject<T>(T objectToSerialize)
{
    using(MemoryStream memStm = new MemoryStream())
    {
        var serializer = new DataContractSerializer(typeof(T));
        serializer.WriteObject(memStm, objectToSerialize);

        memStm.Seek(0, SeekOrigin.Begin);

        using(var streamReader = new StreamReader(memStm))
        {
             string result = streamReader.ReadToEnd();
             return result;
        }
    }
}

Thanks to @xr280xr for pointing out my forgotten StringWriter disposal in the first draft.

/// <summary>
/// Converts this instance to XML.
/// </summary>
/// <returns>XML representing this instance.</returns>
public string ToXml()
{
    var serializer = new DataContractSerializer(this.GetType());
    using (var output = new StringWriter())
    using (var writer = new XmlTextWriter(output) { Formatting = Formatting.Indented })
    {
        serializer.WriteObject(writer, this);
        return output.GetStringBuilder().ToString();
    }
}

And even easier:

var serializer = new DataContractSerializer(typeof(T));
var sb = new StringBuilder();
using (var writer = XmlWriter.Create(sb))
{
    serializer.WriteObject(writer, objectToSerialize);
    writer.Flush();
    return sb.ToString();
}
Ohad Schneider

I suggest combining the methods given by Pat and marc_s:

public static string DataContractSerializeObject<T>(T objectToSerialize)
{
    using (var output = new StringWriter())
    using (var writer = new XmlTextWriter(output) {Formatting = Formatting.Indented})
    {
        new DataContractSerializer(typeof (T)).WriteObject(writer, objectToSerialize);
        return output.GetStringBuilder().ToString();
    }
}

A variant of @root's answer:

var serializer = new DataContractSerializer(typeof(T));
var sb = new StringBuilder();
using (var writer = XmlWriter.Create(sb))
{
    serializer.WriteObject(writer, objectToSerialize);
}

return sb.ToString();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!