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

天大地大妈咪最大 提交于 2019-11-30 20:43:14

You could start by fixing your XML because in the example you have shown you have unclosed tags. You might also wrap the <Building> tags into a <Buildings> collection in order to be able to have other properties in this Location class other than buildings.

<?xml version="1.0" encoding="utf-8" ?>
<info>
  <locations>
    <location name="New York">
      <Buildings>
        <Building name="Building1">
          <Rooms>
            <Room name="Room1">
              <Capacity>18</Capacity>
            </Room>
            <Room name="Room2">
              <Capacity>6</Capacity>
            </Room>
          </Rooms>
        </Building>

        <Building name="Building2">
          <Rooms>
            <Room name="RoomA">
              <Capacity>18</Capacity>
            </Room>
          </Rooms>
        </Building>
      </Buildings>
    </location>
    <location name="London">
      <Buildings>
        <Building name="Building45">
          <Rooms>
            <Room name="Room5">
              <Capacity>6</Capacity>
            </Room>
          </Rooms>
        </Building>
      </Buildings>
    </location>
  </locations>
</info>

Once you have fixed your XML you could adapt your models. I would recommend you using properties instead of fields in your classes:

public class Location
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    public List<Building> Buildings { get; set; }
}

public class Building
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    public List<Room> Rooms { get; set; }
}

public class Room
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    public int Capacity { get; set; }
}

[XmlRoot("info")]
public class Info
{
    [XmlArray("locations")]
    [XmlArrayItem("location")]
    public List<Location> Locations { get; set; }
}

and now all that's left is deserialize the XML:

var serializer = new XmlSerializer(typeof(Info));
using (var reader = XmlReader.Create("locations.xml"))
{
    Info info = (Info)serializer.Deserialize(reader);
    List<Location> locations = info.Locations;
    // do whatever you wanted to do with those locations
}
Dave Kerr

Just use the XML serialization attributes- for example:

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

public class Building
{
     [XmlAttribute("name");
     public string Name;
     public List<Room> 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<Location>));
   var locations = (List<Location>)serializer.Deserialize(stream );
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!