【问题标题】:Deserialize tag with body and attributes to an object将带有主体和属性的标签反序列化为对象
【发布时间】:2013-08-23 06:29:45
【问题描述】:

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

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

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

我试过了:

[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; }
}

该属性反序列化良好但正文为空。我怎样才能反序列化 body 呢?

【问题讨论】:

    标签: c# .net xml-serialization xml-deserialization


    【解决方案1】:

    简单

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

    XmlText 属性完美解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      相关资源
      最近更新 更多