"what is the easiest way to convert this xml document to my object?" Code Answer

2

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
}
By Kamil Gosciminski on February 20 2022

Answers related to “what is the easiest way to convert this xml document to my object?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.