通过DataContractSerializer跳过DataMember

时间:2012-04-10 12:24:08

标签: c# datacontractserializer ignore datamember

我有一个班级:

[DataContract]
public class Result
{
  [DataMember] public String Log {get; set;}
  [DataMember] public String Data {get; set;}
}

我通过WCF发送这个类,它工作正常。但我希望在收到后将此类保存到xml文件中。我试着写:

var serializer = new DataContractSerializer(typeof (T),null,int.MaxValue,
    false,true,null,new SharedTypeXmlResolver());
var settings = new XmlWriterSettings { Indent = true };
using (var backing = new StringWriter(CultureInfo.InvariantCulture))
{
    using (var writer = XmlWriter.Create(backing, settings))
    {
        serializer.WriteObject(writer, result);                                        
    }
    return backing.ToString();
} 

但是我想将“Log”属性保存到xml文件中,并且不想保存“Data”属性。我是怎么做到的 谢谢!

2 个答案:

答案 0 :(得分:0)

XmlIgnore不适用于DataContract序列化。该合同是选择加入,而不是Serializable选择退出。

答案 1 :(得分:0)

使数据可选:

[DataMember(EmitDefaultValue = false)] public String Data {get; set;}

然后删除数据:

result.Data = null;