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 .
XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML serialization.
Xml. Serialization namespace) class is used to serialize and deserialize. The class method Serialize is called. Since we have to serialize in a file, we create a " TextWriter ".
Xml Serializer serializes only public member of object but Binary Serializer serializes all member whether public or private. In Xml Serialization, some of object state is only saved but in Binary Serialization, entire object state is saved.
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); } }
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()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With