1

I am trying to deserialize a string, response.Content, with this XML

<?xml version="1.0" encoding="utf-8"?><root><uri><![CDATA[http://api.bart.gov/api/stn.aspx?cmd=stns]]></uri><stations><station><name>12th St. Oakland City Center</name><abbr>12TH</abbr><gtfs_latitude>37.803664</gtfs_latitude><gtfs_longitude>-122.271604</gtfs_longitude><address>1245 Broadway</address><city>Oakland</city><county>alameda</county><state>CA</state><zipcode>94612</zipcode></station>

I am using this code to deserialize it:

var serializer = new XmlSerializer(typeof(Stations), new XmlRootAttribute("root"));
Stations result;
using (TextReader reader = new StringReader(response.Content))
{
    result = (Stations)serializer.Deserialize(reader);
}

I then have the Stations class declared here

[XmlRoot]
public class Stations
{

    [XmlElement]
    public string name;

}

However, my name is null. Any idea why?

jipot
  • 304
  • 3
  • 13
  • 34
  • 2
    See this post for a good example of what you're trying to do http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document?rq=1 – Iain Ward Jul 27 '15 at 09:11

3 Answers3

3

While using XmlSerializer you should imitate all the xml structure with your classes.

[XmlRoot(ElementName = "root")]
public class Root
{
    [XmlArray(ElementName = "stations"), XmlArrayItem(ElementName = "station")]
    public Station[] Stations { get; set; }
}

public class Station
{
    [XmlElement(ElementName = "name")]
    public string Name { get; set; }
}

Then you can deserialize your data in that way.

var data = ""; //your xml goes here
var serializer = new XmlSerializer(typeof(Root));
using (var reader = new StringReader(data))
{
    var root = (Root)serializer.Deserialize(reader);
}
Uladzislaŭ
  • 1,680
  • 10
  • 13
2

Stations is a list of Station objects. Stations does not have an element called Name, only Station does.

You should probably do something like

   public Station[] Stations

in the root-class.

Then define a new class called Station with a Name property.

Ruben Steins
  • 2,782
  • 4
  • 27
  • 48
  • Would I still need a Stations class? – jipot Jul 27 '15 at 08:52
  • You need a class to hold the Stations property. As long as it's decorated with the XmlRoot attribute I think it should work. – Ruben Steins Jul 27 '15 at 09:03
  • stations = (Station[])serializer.Deserialize(reader); ^getting an error on this line: Unable to cast object of type Station to Station[] – jipot Jul 27 '15 at 09:16
  • You should only have to deserialize the root-object (and let the serializer figure out the rest). See the example in this question: http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document – Ruben Steins Jul 27 '15 at 09:21
2

Stations should not be a class, it should be a collection of Station elements.

mlumeau
  • 821
  • 1
  • 8
  • 20