简体   繁体   中英

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.

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

probably just typo

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

was supposed to be

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

Try to modify your Xml classes like

[XmlRoot(ElementName = "report_metadata")]
public class MetaData
{
    [XmlElement(ElementName = "org_name")]
    public string Organisation { get; set; }
}

[XmlRoot(ElementName = "feedback")]
public class Feedback
{
    [XmlElement(ElementName = "report_metadata")]
    public MetaData MetaData { get; set; }
}

Then you will get your desired output like

class Program
{
    static void Main(string[] args)
    {
        Feedback feedback = new Feedback();
        var xml = System.IO.File.ReadAllText(@"C:\Users\Nullplex6\source\repos\ConsoleApp4\ConsoleApp4\Files\XMLFile1.xml");
        var serializer = new XmlSerializer(typeof(Feedback));
        using (var reader = new StringReader(xml))
        {
            feedback = (Feedback)serializer.Deserialize(reader);
        }

        Console.WriteLine($"Organization: {feedback.MetaData.Organisation}");
        Console.ReadLine();
    }
}

Output:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM