【问题标题】:XmlElement tags ignored for XML Serialization from WCF service忽略来自 WCF 服务的 XML 序列化的 XmlElement 标记
【发布时间】:2015-03-03 03:50:59
【问题描述】:

我正在尝试自定义如何从 WCF 服务序列化我的对象,但是序列化程序忽略了我所有的 [XmlAttribute][XmlElement(DataType="date")] 标记。

public Invoice Get(Int32 Id)
{
    return new Invoice();
}

public class Invoice
{
    [XmlAttribute]
    public string Type { get; set; }

    [XmlElement(DataType="date")]
    public DateTime InvoiceDate { get; set; }
    //..etc
}

当我调用服务时,我得到的响应是:

<Invoice>
    <Type>MyType</Type>
    <InvoiceDate>2015-03-02T22:41:22.5221045-05:00</InvoiceDate>
</Invoice>

我正在寻找的是:

<Invoice Type="MyType">
    <InvoiceDate>2015-03-02</InvoiceDate>
</Invoice>

【问题讨论】:

    标签: c# xml wcf


    【解决方案1】:

    默认情况下,该类将使用 DataContract 序列化程序进行序列化,因此您应该使用...等属性注释您的属性

    [DataContract(Name = "Invoice")]
    public class Invoice
    {
        [IgnoreDataMemberAttribute]
        public string Type { get; set; }
    
        [DataMember(Name = "InvoiceDate ", EmitDefaultValue = false)]
        public DateTime InvoiceDate { get; set;}
    }
    

    DataContract 序列化程序的任何默认属性都不会导致它更改值输出的类型,以便将您的 DateTime 截断为仅一个日期值。要实现这一点,您需要实现 IXmlSerializable 接口,以便您可以详细控制类的序列化和反序列化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-18
      • 2012-03-10
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      相关资源
      最近更新 更多