为什么Xml反序列化中的某些属性总是返回null?

时间:2018-06-12 01:54:33

标签: c# xml deserialization .net-2.0

我想反序列化以下XML文件:

<?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>

。 所以,我写了以下代码:

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

代码正在运行,但每个Type的{​​{1}}和Object属性始终为Argument

此代码有什么问题?

1 个答案:

答案 0 :(得分:2)

更改

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

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