Friday, May 6, 2011

Specifying structure of serialized XML using DataContractSerializer

I am creating serialized XML for a LINQ to SQL project using the DataContractSerializer class. Upon serialization and inspecting the returned object, I get XML that looks like this.

- <ContentObject xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyProject.Data.Model">
  <_x003C_ID_x003E_k__BackingField>1</_x003C_ID_x003E_k__BackingField> 
  <_x003C_ObjectItemState_x003E_k__BackingField>Active</_x003C_ObjectItemState_x003E_k__BackingField> 
  <_x003C_ObjectName_x003E_k__BackingField>6ec555b0ba244ab4a8b2d2f2e7f4185a</_x003C_ObjectName_x003E_k__BackingField>   ETC.

I am trying to find out how to simplify the XML structure to just be

- <ContentObject xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyProject.Data.Model">
  <ID>1</ID> 
  <ObjectItemState>Active</ObjectItemStat> 
  <ObjectName>6ec555b0ba244ab4a8b2d2f2e7f4185a</ObjectName>    ETC

I have tried decorating the wrapper object

 namespace MyProject.Data.Model
{
    [Serializable]
    public class ContentObject
    {
        [XmlAttribute("ID")]
        public int ID { get; set; }
        [XmlAttribute("ObjectName")]
        public string ObjectName { get; set; }   
        [XmlAttribute("ObjectItemState")]
        public string ObjectItemState { get; set; }  ETC
    }
}

but this doesn't help. Can anyone help me find what exactly I need to do to specify the XML structure, either within the class or in the DBML Designer file? Any link or article would be very helpful too. Thanks!

From stackoverflow
  • I found my own answer : I was mixing technology : I needed to change the class decorations as follows:

    [Serializable]
    /// <summary>
    /// regular Object type, like Client or Poll
    /// </summary>
    [DataContract(Name = "ContentObject", Namespace = "http://www.myproject.dev")]
    public class ContentObject
    {
        [DataMember(Name = "ID")]
        public int ID { get; set; }
        [DataMember(Name = "ObjectName")]
        public string ObjectName { get; set; }
        [DataMember(Name = "ObjectItemState")]
        public ItemState ObjectItemState { get; set; } ETC.
    
    marc_s : You beat me to my answer by seconds :-)
  • If you are using the DataContractSerializer as you mentioned, then you have to decorate your structure with [DataContract] and [DataMember] attributes - not [Serializable] and [XmlAttribute] and so forth (those are used for regular and XML serializers).

    The DataContractSerializer is a strictly "opt-in" serializer - only those fields and/or properties that you specifically mark with [DataMember] will end up being serialized; as opposed to the XmlSerializer which is opt-out - it serializes everything unless it's marked with [XmlIgnore].

    Marc

0 comments:

Post a Comment