XML反序列化导致空对象

本文关键字:对象 反序列化 XML | 更新日期: 2023-09-27 18:21:10

我正试图将此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对象有一个长度,所以它正确地提取了文件中的数据,但它从未像我期望的那样填充对象。

XML反序列化导致空对象

更改EMIE的声明如下

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