C# - How to write XML using DataContractSerializer

1 Mark up the class to be serialized with DataContract and DataMember attributes.
2 Pass the type to be serialized to the DataContractSerializer constructor.
3 Create an XmlWriter using XmlWriter.Create().
4 Call DataContractSerializer.WriteObject(writer, object) to serialize object to writer.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
 
namespace Zuga.net
{
    [DataContract]
    public class President
    {
        [DataMember] public int Number { get; set; }
        [DataMember] public string First { get; set; }
        [DataMember] public string Last { get; set; }
        [DataMember] public int Year { get; set; }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            var president = new President()
            {
                Number = 1,
                First = "George",
                Last = "Washington",
                Year = 1789
            };
 
            var serializer = new DataContractSerializer(typeof(President));
 
            var path = "president.xml";
            using (var fs = new FileStream(path, FileMode.Create))
            {
                var writerSettings = new XmlWriterSettings()
                {
                    Indent = true,
                    IndentChars = "    "
                };
 
                using (var writer = XmlWriter.Create(fs, writerSettings))
                {
                    serializer.WriteObject(writer, president);
                }
            }
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<President xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Zuga.net">
  <First>George</First>
  <Last>Washington</Last>
  <Number>1</Number>
  <Year>1789</Year>
</President>

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath