Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...