how to deserialize an xml node with a value and an attribute using asp.net serialization

Sander picture Sander · May 29, 2011 · Viewed 23.1k times · Source

I have 4 small classes to deserialize xml from an incomming xml poll, to usable classes to build up the poll.

now, i know how to set a property from a class, to match a certain attribute or element in the xml, and if that element is just a string thats easy but what if the element also has an attribute like in the following example?

<Questions>
 <Question id="a guid">
  <AnswerItems>
   <AnswerItem Id="a guid">3</AnswerItem>
   <AnswerItem Id="a guid">2</AnswerItem>
   <AnswerItem Id="a guid">5</AnswerItem>
  </AnswerItems>
 </Question>
</Questions>

the question class would look like this:

[Serializable()]
public class Question
{
    [XmlAttribute("Id")]
    public Guid QuestionId { get; set; }

    [XmlArray("AnswerItems")]
    [XmlArrayItem("AnswerItem", typeof(AnswerItem))]
    public AnswerItem[] AnswerItems { get; set; }
}

[Serializable()]
public class AnswerItem
{
    [XmlAttribute("Id")]
    public Guid QuestionId { get; set; }

    // how do i fetch the value of this node? 
    // its not a XmlElement and it's not an XmlValue
}

Ok, so the value of an AnswerItem node, that is what i want to get as well. i could easily not use the AnswerItem class, and just use an XmlArray AnswerItems of the type String and put the values in the array, but then i would lose the AnswerItem's Id Attribute.

Answer

rsbarro picture rsbarro · May 29, 2011

In AnswerItem, make a property called Value and mark it with the XmlText attribute. This setting will cause the XmlSerializer to read the text in the AnswerItem element into the Value property.

[Serializable()]
public class AnswerItem
{
    [XmlAttribute("Id")]
    public Guid QuestionId { get; set; }

    [XmlText]
    public string Value { get; set; }
}