XmlSerializer
is designed to be a very direct translation of your objects to xml; you can use IXmlSerializable
, but it is rarely worth it. You would do better to create objects that mirror the xml structure. Or, simpler - use xsd to do it for you:
xsd example.xml
xsd example.xsd /classes
Or I suspect the following would work (untested):
using System.Collections.Generic;
using System.Xml.Serialization;
public class FavoriteSettings
{
[XmlArray("Customer")]
[XmlArrayItem("ID")]
public List<int> Customers { get; set; }
[XmlArray("Supplier")]
[XmlArrayItem("ID")]
public List<int> Suppliers { get; set; }
}
In particular; if you want the element names ("Customer" etc) to vary based on data ("Name" etc) - then it isn't going to hapopen unless you use IXmlSerializable
, or write it yourself with XDocument
(or similar). For simple data like this, maybe XDocument
is a viable option? But then you make a lot of extra work, especially during deserialization.
Here's an example using your existing class via LINQ-to-XML:
static class Program
{
static void Main() {
var favs = new FavouriteSettings
{
bigList = new List<FavouriteList>
{
new FavouriteList {
Name = "Customer",
aList = new List<int>{
12,2,5
}
}, new FavouriteList {
Name = "Supplier",
aList = new List<int>{
158, 23, 598
}
}
}
};
var el = new XElement("FavoriteSettings",
from fav in favs.bigList
select new XElement(fav.Name,
from item in fav.aList
select new XElement("ID", item)));
string xml = el.ToString();
Console.WriteLine(xml);
el = XElement.Parse(xml);
favs = new FavouriteSettings
{
bigList = new List<FavouriteList>(
from outer in el.Elements()
select new FavouriteList
{
Name = outer.Name.LocalName,
aList = new List<int>(
from id in outer.Elements("ID")
select (int)id
)
})
};
}
}