我有以下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总是变为空....有人可以点燃我吗?
提前致谢
答案 0 :(得分:4)
您应该使用XmlText来获取元素值。这是正确的serialziation属性:
[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" }
]
}
答案 1 :(得分:3)
在visual studio 2013
中:
将您的XML复制到缓冲区中(只需选择它并按CTRL+C
)转到Edit
- &gt; Paste Special
- &gt; Paste XML as Classes