Search code examples
datamember

Rename DataMember during Serialization


I am trying to serialise a DataContract..... I would like to Rename the DataMember.

This is my DataContract

[DataContract(Name = "Sample")]
[Serializable]
public struct Sample
{

        public string CompanyName;


        public string AddressLine;

        [DataMember(Name="AddressLineRename")]
        public string AddressLine2;

        public string City; 

}

it is serialised to:

<Sample>
  <CompanyName>aaa</CompanyName> 
  <AddressLine>16 aaaa</AddressLine> 
  <AddressLine2>Unit 66</AddressLine2> 
  <City>Houston</City> 
</Sample>

what i need is:

<Sample>
  <CompanyName>aaa</CompanyName> 
  <AddressLine>16 aaaa</AddressLine> 
  <AddressLineRename>Unit 66</AddressLineRename> 
  <City>Houston</City> 
</Sample>

I want the "AddressLine2" to be serialised to "AddressLineRename".

Thanks.

Solution

  • This solved to rename the DataMember.

      [DataMember(Order = 2, Name = "AddressLineRename", IsRequired = true)]
      [XmlElement("AddressLineRename")]
      public string AddressLine2;