What is the easiest way to convert this XML document to my object?

后端 未结 2 1291
盖世英雄少女心
盖世英雄少女心 2021-01-05 15:49

I have an XMLDocument that i need to read in and convert into a set of objects. I have the following objects

public class Location
{
      public string Nam         


        
2条回答
  •  逝去的感伤
    2021-01-05 16:46

    Just use the XML serialization attributes- for example:

    public class Location
    {
          [XmlAttribute("name");
          public string Name;
          public List Buildings;
    }
    
    public class Building
    {
         [XmlAttribute("name");
         public string Name;
         public List Rooms;
    }
    

    Just remember - everything will be serialized as XML Elements by default - with the sames the same as the names of the objects :)

    Do this to load:

    using(var stream = File.OpenRead("somefile.xml"))
    {
       var serializer = new XmlSerializer(typeof(List));
       var locations = (List)serializer.Deserialize(stream );
    }
    

提交回复
热议问题