Serialize List Without an Extra Element

1.4k views Asked by At

I can generate the following XML Document however i'm having trouble with the version attribute on the 'ISKeyValueList'element. I am using the xmlSerializer. I should note that this XML is being passed to an API which requires the exact structure as follows.

<Userdata>
  <ISKeyValueList  version="1.00">
     <Item type="String" key="AgeOfDependents">8,6,1<Item/>
     <Item type="Boolean" key="SecuritiesInPosession"> True </Item>
     <Item type="Boolean" key="SecuritiesOwners"> True </item>
  </ISKeyValueList>
</Userdata> 

I have read several stack overflow bounties from which I have learned that to add the version attribute to the list I had to move the list into another class. The following generates the structure above however it adds an extra element which I want to avoid.

C#

UserData newUserData = new UserData();
newUserData.ISKeyValueList = new DataProperties();
newUserData.ISKeyValueList.Items = new List<Item>()
{
   new Item()
   { 
      Type = "String", 
      Key = "AgeOfDependents", 
      //Add data from form
      Value = string.Join(",", application.applicants[0].ageOfDependants)  
    },
    new Item(){ Type = "Boolean", Key = "SecuritiesInPossession", Value = "True" }
    };

newClientDetails.UserData = newUserData;

//Pass object to serializer here

Model

public class UserData
{
    public DataProperties ISKeyValueList { get; set; }
}

public class DataProperties
{
    [XmlAttribute("version")]
    public string Version { get; set; }
    public List<Item> Items { get; set; }

    public DataProperties()
    {
        Version = "1.00";
    }
}

public class Item
{
    [XmlAttribute("type")]
    public string Type { get; set; }
    [XmlAttribute("key")]
    public string Key { get; set; }
    [XmlText]
    public string Value { get; set; }
}

Current Output

enter image description here

However this add extra, unwanted element (highlighted above) to the XML Document. Is there a way I can remove this extra element by configuring the model as i'd rather avoid setting up custom serializers etc.

1

There are 1 answers

0
Sacrilege On BEST ANSWER

Add the attribute [XmlElement("Item")] to your DataProperties.Items property.