Search code examples
c#xmlxml-parsingxmlserializer

How to deserialize an XML with attributes in C#


I have an XML file that looks something similar to this:

<data label="product data">
    <price min="10" max="60">35</price>
</data>

I'm using System.Xml.Serialization in .Net Core. I'm trying to Deserialize the XML. For regular XML like this:

<data>
   <price>35</price>
</data>

The following method:

public T DeserializeXml<T>(string input)
{
    var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

    using var stringReader = new StringReader(input);
    var xmlReader = new XmlTextReader(stringReader);
    return (T) xmlSerializer.Deserialize(xmlReader);
}

Works fine and parses it into its specific class object. But when the XML contains attributes, it's not working fine and while trying to deserialize it into it's object it crashes.

This is my class:

[XmlType("data")]
public class ProductInfo
{
    [XmlElement(ElementName = "price")]
    public string Price{ get; set; }
}

So how can I retreive a valid XML with attributes and how to store its attributes values? Not sure on how to do it using System.Xml.Serialization library.


Solution

  • By looking at the XML the model should look like

    [XmlRoot(ElementName="price")]
    public class Price {
        [XmlAttribute(AttributeName="min")]
        public string Min { get; set; }
        [XmlAttribute(AttributeName="max")]
        public string Max { get; set; }
        [XmlText]
        public string Text { get; set; }
    }
    
    [XmlRoot(ElementName="data")]
    public class Data {
        [XmlElement(ElementName="price")]
        public Price Price { get; set; }
        [XmlAttribute(AttributeName="label")]
        public string Label { get; set; }
    }