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

﹥>﹥吖頭↗ 提交于 2019-11-29 05:59:40
Ventsyslav Raikov

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";
}

This can be useful for you. When you need XElement. For instance when you going append node to XDocument or replece XElement of this document.

private XElement objectToXElement(SomeContractType obj)
        {
            DataContractSerializer dcs = new DataContractSerializer(typeof(SomeContractType);

            var ms = new MemoryStream();
            var xw = XmlWriter.Create(ms);
            dcs.WriteObject(xw, obj);
            xw.Flush();
            xw.Close();
            ms.Position = 0;
            XElement xe = XElement.Load(ms);

            return xe;
        }
Mare Infinitus

There is the NetDataContractSerializer which solves a whole bunch of problems when using WCF.

See here MSDN NetDataContractSerializer

It is typically used for wrapping all kinds of objects and pass it over WCF.

You can use it for wrapping objects into a byte[] and transport it over WCF, on the serverside, you can easily Deserialize the objects and do whatever you want with them.

Here is a discussion on how to use this Serializer correctly: MSDN Social

Code snippets are provided there also!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!