29

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.

Sander
  • 13,301
  • 15
  • 72
  • 97

1 Answers1

77

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; }
}
rsbarro
  • 27,021
  • 9
  • 71
  • 75
  • 5
    Just wanted to post that, I have been looking for an answer to a similar question, and this is the first one that showed me anything like this in all of stack... I'd give +10 if I could <3 – Jeremy Walker May 02 '17 at 05:49
  • 1
    Yes, thank you, oldie but a goodie and does not come up when searching! – Vale Trujillo Jun 21 '19 at 18:47
  • 1
    Great answer. Although I read on some other post on SO that Serializable() attribute is not considered by Serializer and similarly my class does not have such attribute. Yet the code works just fine. :) – Imran Faruqi Dec 31 '20 at 09:49