Search code examples
c#xmldeserialization.net-2.0

Why do some attributes in Xml deserialization always return null?


I want to deserialize the following XML file:

<?xml version="1.0" encoding="utf-8"?>
<function xmlns="urn:google.com" >
  <file>my.xml</file>
  <name>My</name>
  <arguments>
    <argument type="int" object="a"/>
    <argument type="char" object="b"/>
  </arguments>
  <return_type>int</return_type>
  <sql>MySql</sql>
  <content>xyz</content>
</function>

. So, I have written the following code:

public class Argument 
{
    [XmlAttribute("type")]
    public string Type { get; set; }

    [XmlAttribute("object")]
    public string Object { get; set; }
}

[XmlRoot("function", Namespace = "urn:google.com")]
public class Function
{
    [XmlElement("file")]
    public string File { get; set; }

    [XmlElement("name")]
    public string Name { get; set; }

    [XmlElement("sql")]
    public string Sql { get; set; }

    [XmlElement("return_type")]
    public string ReturnType{ get; set; }

    [XmlElement("arguments")]
    public List<Argument> Arguments { get; set; }

    [XmlElement("content")]
    public string Content { get; set; }

    public static Function Deserialize(string fullPath)
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(Function));
        TextReader reader = new StreamReader(fullPath);
        object obj = deserializer.Deserialize(reader);

        Function f = (Function)obj;
        reader.Close();

        return f;
    }
}

The code is working except Type and Object properties of each Argument are always null.

What is wrong with this code?


Solution

  • Change

    [XmlElement("arguments")]
    public List<Argument> Arguments { get; set; }
    

    to

    [XmlArray("arguments")]
    [XmlArrayItem("argument")]
    public List<Argument> Arguments { get; set; }