John P
John P

Reputation: 1580

XmlElement tags ignored for XML Serialization from WCF service

I'm trying to customize how my object is being serialized from a WCF service, however the serializer is ignoring all my [XmlAttribute] and [XmlElement(DataType="date")] tags.

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
}

When I call the service, the response I get back is:

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

What I'm looking for is:

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

Upvotes: 1

Views: 978

Answers (1)

Phil Wright
Phil Wright

Reputation: 22926

By default the class will be serialized using the DataContract serializer and so you should be annotating your properties with attributes such as ...

[DataContract(Name = "Invoice")]
public class Invoice
{
    [IgnoreDataMemberAttribute]
    public string Type { get; set; }

    [DataMember(Name = "InvoiceDate ", EmitDefaultValue = false)]
    public DateTime InvoiceDate { get; set;}
}

None of the default attributes for the DataContract serializer will cause it to change the type of the value output, in order to truncate your DateTime to just a date value. To achieve this you would need to implement the IXmlSerializable interface so you can control the serialization and deserialization of the class at a detailed level.

Upvotes: 2

Related Questions