John B
John B

Reputation: 20400

Can I Serialize XML straight to a string instead of a Stream with C#?

This example uses a StringWriter to hold the serialized data, then calling ToString() gives the actual string value:

Person john = new Person();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person));
StringWriter stringWriter = new StringWriter();
xmlSerializer.Serialize(stringWriter, john);
string serializedXML = stringWriter.ToString();

Is there any easier/Cleaner way to do this? All of the Serialize() overloads seem to use a Stream or Writer.

UPDATE: Asked a similar question about serializing an IEnumerable via an Extension Method .

Upvotes: 24

Views: 38583

Answers (4)

Necromancer
Necromancer

Reputation: 430

Seems like no body actually answered his question, which is no, there is no way to generate an XML string without using a stream or writer object.

Upvotes: 5

John B
John B

Reputation: 20400

I created this helper method, but I haven't tested it yet. Updated the code per orsogufo's comments (twice):

private string ConvertObjectToXml(object objectToSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());
    StringWriter stringWriter = new StringWriter();

    xmlSerializer.Serialize(stringWriter, objectToSerialize);

    return stringWriter.ToString();
}

Upvotes: 6

Paolo Tedesco
Paolo Tedesco

Reputation: 57302

More or less your same solution, just using an extension method:

static class XmlExtensions {

    // serialize an object to an XML string
    public static string ToXml(this object obj) {
        // remove the default namespaces
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add(string.Empty, string.Empty);
        // serialize to string
        XmlSerializer xs = new XmlSerializer(obj.GetType());
        StringWriter sw = new StringWriter();
        xs.Serialize(sw, obj, ns);
        return sw.GetStringBuilder().ToString();
    }

}

[XmlType("Element")]
public class Element {
    [XmlAttribute("name")]
    public string name;
}

class Program {
    static void Main(string[] args) {
        Element el = new Element();
        el.name = "test";
        Console.WriteLine(el.ToXml());
    }
}

Upvotes: 7

Matthew Whited
Matthew Whited

Reputation: 22443

Fun with extension methods...

var ret = john.ToXmlString()

public static class XmlTools
{
    public static string ToXmlString<T>(this T input)
    {
        using (var writer = new StringWriter())
        {
            input.ToXml(writer);
            return writer.ToString();
        }
    }
    public static void ToXml<T>(this T objectToSerialize, Stream stream)
    {
        new XmlSerializer(typeof(T)).Serialize(stream, objectToSerialize);
    }

    public static void ToXml<T>(this T objectToSerialize, StringWriter writer)
    {
        new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
    }
}

Upvotes: 45

Related Questions