【问题标题】:XML Deserialization results in empty objectXML反序列化导致空对象
【发布时间】:2014-09-08 20:52:03
【问题描述】:

我正在尝试将此 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 对象有一个长度,因此它可以正确获取文件中的数据,但它永远不会像我期望的那样填充对象。

【问题讨论】:

    标签: c# xml deserialization


    【解决方案1】:

    修改EMIE的声明如下

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

    【讨论】:

    • 哇,好电话我在某处读到,您必须将其指定为 [XmlArrayItem("name")]。但这有效。谢谢!
    • @L.B 您能否简要解释一下为什么会这样? List Paths { 上的属性是否会获取;放; } 也必须改为 XmlElement 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多