I am trying to serialize several lists of objects to xml. The lists are of different types but they all need to have some the same attributes on the top list object.
What I am trying to get is a ‘count’ on the top level and the name of the object for all the items in the list:
<JobResult Count="2">
<Job>
<Id>1</Id>
</Job>
<Job>
<Id>2</Id>
</Job>
</JobResult>
Then for another list:
<PersonResult Count="1">
<Person>
<Id>1</Id>
</Person>
</PersonResult>
The code I am using is:
[XmlRoot()]
public class Result<T>
{
[XmlElement()]
public List<T> Items { get; set; }
public Result()
{
this.Items = new List<T>();
}
[XmlAttribute("Count")]
public int ItemCount
{
get
{
return this.Items.Count;
}
set
{
}
}
}
var jobs= new Result<Job>();
var persons= new Result<Person>();
What I am getting is:
<ResultOfJob Count="2">
<Item>
<Id>1</Id>
</Item>
<Item>
<Id>2</Id>
</Item>
</ResultOfJob >
I have tried the attribute naming like this but get <_x007B_0_x007D_> instead of item.
[XmlElement({0})]
public List<T> Items { get; set; }
What is the best way to handle naming the items dynamically?
The way I ended up solving this is creating the result class in a similar fashion:
And then I Inherit this class for any object that I need to have the common ResultCount as an attribute. If I need to add any other common attributes to all of the results objects I can do it through the above Result class.
Here Is an example inherited class:
The [XmlIgnore] on the List in the Result class allows me to specify the name of the list items in the derived class with the [XmlElement] attribute.