如何序列化/反序列化 C# WCF DataContract 到/从 XML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11142280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:41:32  来源:igfitidea点击:

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

c#wcfxml-serializationdeserializationdatacontract

提问by temelm

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.

我正在开发一个 WCF 服务,它将被多个不同的客户端应用程序使用。为了使一项功能起作用,服务器需要将 XML 文件读入 C# DataContract,然后将其传递给相关客户端。据我从 MSDN 网站了解,这是可能的,但我找不到任何完整的示例。特别是,该网站谈到了一个我还不太明白的“流”参数。

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.

我的课程看起来像这样。

采纳答案by 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";
}

回答by Mare Infinitus

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

NetDataContractSerializer 解决了使用 WCF 时的一大堆问题。

See here MSDN NetDataContractSerializer

请参阅此处MSDN NetDataContractSerializer

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

它通常用于包装各种对象并通过 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.

您可以使用它将对象包装到 a 中byte[]并通过 WCF 传输它,在服务器端,您可以轻松地反序列化对象并使用它们做任何您想做的事情。

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

以下是有关如何正确使用此序列化程序的讨论: MSDN Social

Code snippets are provided there also!

那里也提供了代码片段!

回答by trueboroda

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.

这对你很有用。当您需要 XElement 时。例如,当您将节点附加到 XDocument 或替换此文档的 XElement 时。

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