XML反序列化导致空对象

时间:2014-09-08 20:52:03

标签: c# xml deserialization

我试图将此XML文件反序列化为对象

<?xml version="1.0" encoding="utf-8" ?>
<rules version="3">
  <emie>
    <domain>msdn.microsoft.com</domain>
    <domain exclude="false">
      bing.com
      <path exclude="true">images</path>
    </domain>
    <domain exclude="true">
      news.msn.com
      <path exclude="false">pop-culture</path>
    </domain>
    <domain>timecard</domain>
    <domain>tar</domain>
  </emie>
</rules>

我的对象布局如此

[XmlRoot("rules")]
public class Rules {
    [XmlAttribute("version")]
    public string Version { get; set; }

    [XmlElement("emie")]
    public EMIE EMIE { get; set; }
}

public class EMIE {
    [XmlArrayItem("Domain")]
    public List<Domain> Domains { get; set; }
}

public class Domain {
    [XmlAttribute("exclude")]
    public bool Exclude { get; set; }
    [XmlText]
    public string Value { get; set; }
    [XmlArrayItem("Path")]
    public List<Path> Paths { get; set; }
}

public class Path {
    [XmlAttribute]
    public bool Exclude { get; set; }
    [XmlText]
    public string Value { get; set; }
}

我正在使用此代码对其进行反序列化

    static void Main(string[] args) {
        XmlSerializer serializer = new XmlSerializer(typeof(Rules));

        using (FileStream stream = new FileStream("EM.xml", FileMode.Open)) {
            Rules xml = (Rules)serializer.Deserialize(stream);

            foreach (Domain d in xml.EMIE.Domains) {
                Console.WriteLine(d.Value);
                foreach (EnterpriseModeModel.Path p in d.Paths) {
                    Console.WriteLine(p.Value);
                }
            }
        }

        Console.ReadLine();
    }

但是,我的rules.EMIE.Domains对象始终为空。当我调试时,我可以看到我的stream对象有一个长度,所以它正确地拾取文件中的数据,但它永远不会像我期望的那样填满对象。

1 个答案:

答案 0 :(得分:1)

更改EMIE的声明如下

public class EMIE
{
    [XmlElement("domain")]
    public List<Domain> Domains { get; set; }
}