在没有属性的情况下反序列化XML
本文关键字:情况下 反序列化 XML 属性 | 更新日期: 2023-09-27 17:50:12
我有以下XML,但无法反序列化到所需的对象。
<response>
<texts>
<text name="blabla">This is bla</text>
<text name="test xpto">This is a text</text>
(…)
</texts>
</response>
这就是我迄今为止所尝试的:
public class ResponseTexts : Response
{
[XmlArray(ElementName = "texts")]
[XmlArrayItem(ElementName = "text"]
public List<Text> Texts { get; set; }
}
public class Text
{
[XmlElement(ElementName = "text")]
public string TextValue { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
}
但到目前为止,TextValue总是为null。。。。有人能照亮我吗?
提前感谢
您应该使用XmlText来获取元素值。以下是正确的序列化属性:
[XmlRoot("response")]
public class Response
{
[XmlArray(ElementName = "texts")]
[XmlArrayItem(ElementName = "text")]
public List<Text> Texts { get; set; }
}
public class Text
{
[XmlText]
public string TextValue { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
}
反序列化:
var serializer = new XmlSerializer(typeof(Response));
using(var stream = File.OpenRead(path_to_xml))
{
var response = (Response)serializer.Deserialize(stream);
}
结果:
{
Texts: [
{ TextValue: "This is bla", Name: "blabla" },
{ TextValue: "This is a text", Name: "test xpto" }
]
}
在visual studio 2013
中:在缓冲区中复制XML(只需选择它并按CTRL+C
(转到Edit
->Paste Special
->Paste XML as Classes