I am looking to properly deserialize some XML.
Part of the XML looks like this:
<Keys>
<Key>
<Name>Test 1</Name>
<KeyValues>
<KeyValue Offered="true" Order="1">One</KeyValue>
<KeyValue Offered="true" Order="2">Two</KeyValue>
<KeyValue Offered="true" Order="3">Three</KeyValue>
<KeyValue Offered="true" Order="4">Four</KeyValue>
</KeyValues>
</Key>
<Key>
<Name>Test 2</Name>
<KeyValues>
<KeyValue Offered="true">One</KeyValue>
</KeyValues>
</Key>
</Keys>
and I would like to deserialize each KeyValue from that into a C# object that looks like this:
public class KeyValue
{
public string Value { get; set; }
[XmlAttribute]
public int Order { get; set; }
[XmlAttribute]
public bool Offered { get; set; }
}
This is (roughly) the code that I am using to deserialize:
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
using (TextReader reader = new StringReader(xml))
{
myObject = (MyObject)serializer.Deserialize(reader);
}
This is almost working properly. No exceptions are thrown and Order and Offered are correctly set, but I'd like the One, Two, Three, etc from the KeyValues in my XML to go into the Value field on my model.
Is this possible? If so, how could I do it?
After taking a look at this website per Robert Harvey's comment, I realized that what I was missing was an [XmlText]
attribute over my Value field. I added that, tested, and it worked.