Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 960
Sander Avatar asked May 29 '11 16:05

Sander


1 Answers

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; } } 
like image 176
rsbarro Avatar answered Sep 24 '22 20:09

rsbarro