Search code examples
c#xml-deserialization

Null value on xml deserialization using [XmlAttribute]


I have the following XML;

<?xml version="1.0" encoding="UTF-8" ?>
<feedback>
  <report_metadata>
    <org_name>example.com</org_name>
  </report_metadata>
</feedback>

and the following Feedback.cs class;

   [XmlRoot("feedback", Namespace = "", IsNullable = false)]
    public class Feedback
    {
        [XmlElement("report_metadata")]
        public MetaData MetaData { get; set; }
    }


    [XmlType("report_metadata")]
    public class MetaData
    {
        [XmlAttribute("org_name")]
        public string Organisation { get; set; }
    }

When I attempt to deserialize, the value for Organisation is null.

var xml = System.IO.File.ReadAllText("example.xml");
var serializer = new XmlSerializer(typeof(Feedback));
using (var reader = new StringReader(input))
{
    var feedback = (Feedback)serializer.Deserialize(reader);

}

Yet, when I change Feedback.cs to the following, it works (obviously the property name has changed).

[XmlType("report_metadata")]
public class MetaData
{
    //[XmlAttribute("org_name")]
    public string org_name { get; set; }
}

I want the property to be Organisation, not org_name.


Solution

  • In the example XML file org_name is an XML element, not an XML attribute. Changing [XmlAttribute("org_name")] to [XmlElement("org_name")] at the Organisation property will deserialize it as an element:

    [XmlElement("org_name")]
    public string Organisation { get; set; }