Deserialize tag with body and attributes to an object

五迷三道 提交于 2021-02-05 08:17:25

问题


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.

I've tried:

[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?


回答1:


Simply

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

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

XmlText attribute worked out perfectly.



来源:https://stackoverflow.com/questions/18396247/deserialize-tag-with-body-and-attributes-to-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!