不带属性的反序列化XML

sexta13

我有以下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。...有人可以启发我吗?

提前致谢

谢尔盖·别列佐夫斯基(Sergey Berezovskiy)

您应该使用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" }
  ]
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章