C# - How to read 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 Call DataContractSerializer.ReadObject() to deserialize the object from the stream.
using System.IO;
using System.Runtime.Serialization;
namespace Zuga.net
    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 serializer = new DataContractSerializer(typeof(President));
            var path = "president.xml";
            using (var fs = new FileStream(path, FileMode.Open))
                var president = (President)serializer.ReadObject(fs);
<?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">

Ads by Google

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

© Richard McGrath