How do you serialize the following
[XmlRoot("response")]
public class MyCollection<T>
{
[XmlElement("person", Type = typeof(Person))]
public List<T> entry;
public int startIndex;
}
where T can be a class like
public class Person
{
public string name;
}
into
<response>
<startIndex>1</startIndex>
<entry>
<person>
<name>meeee</name>
</person>
</entry>
<entry>
<person>
<name>youuu</name>
</person>
</entry>
</response>
I have been playing with [XmlArray], [XmlArrayItem], and [XmlElement] and I can't seem to get the right combination. Arrrgghhh.
Update:
[XmlArray("entry")]
[XmlArrayItem("person", Type = typeof(Person))]
public List<T> entry;
gives me
<entry><person></person><person></person></entry>
[XmlElement("person", Type = typeof(Person))]
public List<T> entry;
gives me
<person></person><person></person>
I can't see any obvious way of getting it to output those results without changing the classes radically... this might not be what you want, but by mirroring the desired output (not uncommon in DTOs) it gets the right result...
Otherwise, you might be looking at IXmlSerializable
, which is a huge pain:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
[XmlRoot("response")]
public class MyResponse {
public MyResponse() {
Entries = new List<Entry>();
}
[XmlElement("startIndex", Order = 1)]
public int StartIndex { get; set; }
[XmlElement("entry", Order = 2)]
public List<Entry> Entries { get; set; }
}
public class Entry {
public Entry() { }
public Entry(Person person) { Person = person; }
[XmlElement("person")]
public Person Person { get; set; }
public static implicit operator Entry(Person person) {
return person == null ? null : new Entry(person);
}
public static implicit operator Person(Entry entry) {
return entry == null ? null : entry.Person;
}
}
public class Person {
[XmlElement("name")]
public string Name { get; set; }
}
static class Program {
static void Main() {
MyResponse resp = new MyResponse();
resp.StartIndex = 1;
resp.Entries.Add(new Person { Name = "meeee" });
resp.Entries.Add(new Person { Name = "youuu" });
XmlSerializer ser = new XmlSerializer(resp.GetType());
ser.Serialize(Console.Out, resp);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With