Search code examples
c#.netxmllinq-to-xmlxelement

Convert single XElement to object


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?


Solution

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