简体   繁体   中英

XML Deserialization results in empty object

I'm attempting to deserialize this XML file into an object

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

I have my objects laid out like so

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

And am using this code to deserialize it

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

However, my rules.EMIE.Domains object is always empty. When I debug I can see my stream object has a length so it's properly picking up the data in the file but it never fills up the object like I expect it to.

Change the declaration of EMIE as follows

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM