xml serializer c# code example

Example 1: c# serialize to xml

XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
 var subReq = new MyObject();
 var xml = "";

 using(var sww = new StringWriter())
 {
     using(XmlWriter writer = XmlWriter.Create(sww))
     {
         xsSubmit.Serialize(writer, subReq);
         xml = sww.ToString(); // Your XML
     }
 }

Example 2: XML Serialization

/// 
/// Converts an object to its serialized XML format.
/// 
/// The type of object we are operating on
/// The object we are operating on
/// Whether or not to remove the default XML namespaces from the output
/// Whether or not to omit the XML declaration from the output
/// The character encoding to use
/// The XML string representation of the object
public static string ToXmlString(this T value, bool removeDefaultXmlNamespaces = true, bool omitXmlDeclaration = true, Encoding encoding = null) where T : class
{
    XmlSerializerNamespaces namespaces = removeDefaultXmlNamespaces ? new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }) : null;
 
    var settings                = new XmlWriterSettings();
    settings.Indent             = true;
    settings.OmitXmlDeclaration = omitXmlDeclaration;
    settings.CheckCharacters    = false;
 
    using (var stream = new StringWriterWithEncoding(encoding))
    using (var writer = XmlWriter.Create(stream, settings))
    {
        var serializer = new XmlSerializer(value.GetType());
        serializer.Serialize(writer, value, namespaces);
        return stream.ToString();
    }
}

Tags:

Misc Example