Convert single XElement to object

Numm3n picture Numm3n · Sep 4, 2013 · Viewed 20.6k times · Source

I have a single XElement looking like this:

<row flag="1" sect="" header="" body="" extrainfo="0" />

Then I have a class looking like this:

public class ProductAttribute
{
    public string Flag { get; set; }
    public string Sect { get; set; }
    public string Header { get; set; }
    public string Body { get; set; }
    public string Extrainfo { get; set; }
}

How can I convert this XElement into a ProductAttribute object?

Answer

jbl picture jbl · Sep 4, 2013

You have to put the correct serialization attributes on your class and class members

[Serializable()]
[XmlRoot(ElementName = "row")]
public class ProductAttribute
{
    [XmlAttribute("flag")]
    public string Flag { get; set; }
    [XmlAttribute("sect")]
    public string Sect { get; set; }
    [XmlAttribute("header")]
    public string Header { get; set; }
    [XmlAttribute("body")]
    public string Body { get; set; }
    [XmlAttribute("extrainfo")]
    public string Extrainfo { get; set; }
}