Convert single XElement to object Convert single XElement to object xml xml

Convert single XElement to object


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


You could do this way:

1) At first you should give attributes to the class:

[XmlRoot("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; }}

2) Now you can deserialize your XElement or simple xml string like this:

ProductAttribute productAttribute = new ProductAttribute();XElement xElement = XElement.Parse("<row flag='1' sect='3' header='4444' body='3434' extrainfo='0' />");//StringReader reader = new StringReader(//"<row flag='1' sect='3' header='4444' body='3434' extrainfo='0' />");StringReader reader = new StringReader(xElement.ToString());XmlSerializer xmlSerializer = new XmlSerializer(typeof(ProductAttribute));productAttribute = (ProductAttribute)xmlSerializer.Deserialize(reader);

I hope it helps you.


Have you tried:

XElement element = //Your XElementvar serializer = new XmlSerializer(typeof(ProductAttribute));(ProductAttribute)serializer.Deserialize(element.CreateReader())