I have the following XML which needs deserializing/serializing:
<instance>
<dog>
<items>
<item>
<label>Spaniel</label>
</item>
</items>
</dog>
<cat>
<items>
<item>
<label>Tabby</label>
</item>
</items>
</cat>
</instance>
I cannot change the XML structure.
I need to map this to the following class:
[Serializable, XmlRoot("instance")]
public class AnimalInstance
{
public string Dog { get; set; }
public string Cat { get; set; }
}
I'm not really sure where to start on this one without manually parsing the XML. I'd like to keep the code as brief as possible. Any ideas? (and no, my project doesn't actually involve cats and dogs).
A simple working example (skipping the cat for brevity) using System.Xml.Serialization:
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
[XmlRoot("instance")]
public class AnimalInstance {
[XmlElement("dog")]
public Dog Dog { get; set; }
}
public class Dog {
[XmlArray("items")]
[XmlArrayItem("item")]
public List<Item> Items = new List<Item>();
}
public class Item {
[XmlElement("label")]
public string Label { get; set; }
}
class Program {
static void Main(params string[] args) {
string xml = @"<instance>
<dog>
<items>
<item>
<label>Spaniel</label>
</item>
</items>
</dog>
</instance>";
XmlSerializer xmlSerializer = new XmlSerializer(typeof(AnimalInstance));
AnimalInstance instance = (AnimalInstance)xmlSerializer.Deserialize(new StringReader(xml));
}
}
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