将带有主体和属性的标记反序列化为对象 [英] Deserialize tag with body and attributes to an object

查看:29
本文介绍了将带有主体和属性的标记反序列化为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将这样的 XML 反序列化为对象:

How can I deserialize XML like that to an object:

<Root>
   <Element Attr="AttrValue1">BodyValue1</Element>
   <Element Attr="AttrValue2">BodyValue2</Element>
   <Element Attr="AttrValue3">BodyValue3</Element>
</Root>

我需要具有适当属性的确切对象结构.

I need the exact objects structure with appropriate attributes.

我试过了:

[XmlRoot("Root")]
public class EventFieldsRoot
{
    [XmlElement("Element")]
    public List<Element> Elements{ get; set; }
}

public class Element
{
    [XmlAttribute]
    public string Attr { get; set; }

    [XmlElement("")]
    public string Body { get; set; }
}

属性反序列化良好,但主体为空.我怎样才能反序列化身体?

The attribute deserializes good but body is empty. How can I deserialize body as well?

推荐答案

简单

public class Element
{
    [XmlAttribute]
    public string Attr { get; set; }

    [XmlText]
    public string Body { get; set; }
}

XmlText 属性完美无缺.

XmlText attribute worked out perfectly.

这篇关于将带有主体和属性的标记反序列化为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆