Search code examples
c#wcfxml-serializationdeserializationdatacontract

How to serialize/deserialize a C# WCF DataContract to/from XML


I am developing a WCF service which will be consumed by multiple different client applications. In order to make one functionality work, the server needs to read an XML file into a C# DataContract which is then passed on to the concerned client. As far as I understand from the MSDN website, this is possible but I couldn't find any complete examples. In particular, the website talks about a 'stream' parameter which I don't quite get yet.

My data contract has one property field which is a list of another data contract which has multiple simple property fields.

e.g.

    [DataContract]
    public class MyClass1 {
        [DataMember]
        public string name;
        [DataMember]
        public int age;
    }

    [DataContract]
    public class MyClass2 {
        [DataMember]
        public List<MyClass1> myClass1List;
    }

My classes look something like this.


Solution

  • Here is an example

    MyClass1 obj = new MyClass1();
    DataContractSerializer dcs = new DataContractSerializer(typeof(MyClass1));
    
    using (Stream stream = new FileStream(@"C:\tmp\file.xml", FileMode.Create, FileAccess.Write))
    {
        using (XmlDictionaryWriter writer = 
            XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
        {
            writer.WriteStartDocument();
            dcs.WriteObject(writer, obj);
        }
    }
    

    Books b = new Books();
    
    DataContractSerializer dcs = new DataContractSerializer(typeof(Books));
    
    try
    {
        Stream fs = new FileStream(@"C:\Users\temelm\Desktop\XmlFile.xml", FileMode.Create, FileAccess.Write);
    
        XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(fs, Encoding.UTF8);
        xdw.WriteStartDocument();
        dcs.WriteObject(xdw, b);
        xdw.Close();
        fs.Flush();
        fs.Close();
    }
    catch (Exception e)
    {
        s += e.Message + "\n";
    }