This example uses a StringWriter
to hold the serialized data, then calling ToString()
gives the actual string
value:
P
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();
}
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);
}
}
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.
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());
}
}