如何使用asp.net序列化对值为xml的节点和属性进行反序列化 [英] how to deserialize an xml node with a value and an attribute using asp.net serialization
问题描述
我有4个小类,用于反序列化xml从一个传入的xml轮询,到可用的类建立轮询。
现在,我知道如何设置属性从一个类,匹配xml中的某个属性或元素,如果该元素只是一个容易
的字符串,但如果该元素也有一个属性,如下面的例子?
<问题>
< 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>
问题类应如下所示:
[Serializable()]
public class Question
{
[XmlAttribute(Id)]
public Guid QuestionId {get;组; }
[XmlArray(AnswersItems)]
[XmlArrayItem(AnswerItem,typeof(AnswerItem))]
public AnswerItem [] AnswerItems {get;组; }
}
[Serializable()]
public class AnswerItem
{
[XmlAttribute(Id)]
public Guid QuestionId {get;组; }
//如何获取此节点的值?
//它不是XmlElement,它不是XmlValue
}
Ok ,因此一个AnswerItem节点的值,这也是我想要得到的。
i可以很容易地不使用AnswerItem类,只是使用类型String的XmlArray AnswerItems,并将值放在数组中,但是我将失去AnswerItem的Id属性。
AnswerItem
中,创建一个名为 Value
的属性使用 XmlText
属性标记它。此设置将使 XmlSerializer
将 AnswerItem
元素中的文本读入 Value
。 [Serializable()]
public class AnswerItem
{
[XmlAttribute(Id)]
public Guid QuestionId {get;组; }
[XmlText]
public string Value {get;组; }
}
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.
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; }
}
这篇关于如何使用asp.net序列化对值为xml的节点和属性进行反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!