Reputation: 2304
Essentially, I need to serialize a C# object to an xml document with an entirely different xml structure and different class/node names. The structure of the C# class is:
public class Root
{
public item item {get; set}
}
public class item
{
public string name {get; set}
public color[] color
}
public class color
{
public string itemColor {get; set}
}
Lets say our item is a car. This serializes to
<Root>
<item>
<name>car</name>
<color>
<itemColor>red</itemColor>
<itemColor>blue</itemColor>
<itemColor>gree</itemColor>
</Color>
</item>
</Root>
But I need this to serialize to:
<Root>
<item>
<name>car</name>
<itemColor>red</itemColor>
</item>
<name>car</name>
<itemColor>blue</itemColor>
</item>
<item>
<name>car</name>
<itemColor>green</itemColor>
</item>
</Root>
I'm currently using IXmlSerializable to try and specify a schema. What is the optimal way of doing this? Should I convert to a second custom object?
Upvotes: 0
Views: 187
Reputation: 14251
Try this:
public class Root
{
[XmlIgnore]
public item item { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
[XmlAnyElement("item")]
public List<XElement> _item
{
get
{
return item.color.Select(i =>
new XElement("item",
new XElement("name", item.name),
new XElement("itemColor", i.itemColor)
)).ToList();
}
}
}
public class item
{
public string name { get; set; }
public color[] color;
}
public class color
{
public string itemColor { get; set; }
}
Also, it would be better to use nameof
instead of hardcoded literals.
[XmlAnyElement(nameof(item))]
public List<XElement> _item
{
get
{
return item.color.Select(i =>
new XElement(nameof(item),
new XElement(nameof(item.name), item.name),
new XElement(nameof(i.itemColor), i.itemColor)
)).ToList();
}
}
Upvotes: 1