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

5

43

I had a quick question regarding the datacontractserializer. Maybe it's more of a stream question. I found a piece of code that writes the xml to a filestream. I basically don't want the file and just need the string output.

public static string DataContractSerializeObject<T>(T objectToSerialize)
{   
    var fs = new FileStream("test.xml", FileMode.OpenOrCreate);
    var serializer = new DataContractSerializer(typeof(T));
    serializer.WriteObject(fs, objectToSerialize);
    fs.Close();
    return fs.ToString();
}

fs.ToString() is obviously not what I'm looking for. What stream or writer etc, can I use just to return the proper string and not create a file? I did look at the XML the filestream created and it's exactly what I'm looking for. The XmlSerializer wrote the XML a bit strange and I prefer the output of the DataContractSerializer in this case. Can anyone point me in the right direction?

Deach answered 13/7, 2010 at 15:33 Comment(0)
C
74

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;
        }
    }
}
Chondrule answered 13/7, 2010 at 15:37 Comment(2)
Looks like you interchanged the parameter, it should be memStm.Seek(0,SeekOrigin.Begin);Brufsky
@xar: yes, you're absolutely right - thanks for spotting that mistake - I fixed it nowChondrule
S
29

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();
    }
}
Sheikdom answered 6/8, 2010 at 14:35 Comment(3)
Your StringWriter should be disposed as well.Daw
The stacked usings do just that.Inductee
This would also make a great extension method for DataContractSerializer (and analogously for XmlSerializer). public static string WriteObjectToString(this DataContractSerializer serializer, object obj){...}Rhizomorphous
H
20

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();
}
Heteropterous answered 14/3, 2013 at 14:14 Comment(0)
T
3

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();
    }
}
Triptolemus answered 28/5, 2013 at 20:31 Comment(1)
This is Pat's method with marc_s's method signature.Sonority
P
2

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();
Pile answered 12/11, 2015 at 22:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.