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?
Stations
should not be a class, it should be a collection ofStation
elements.While using
XmlSerializer
you should imitate all the xml structure with your classes.Then you can deserialize your data in that way.
Stations is a list of Station objects. Stations does not have an element called Name, only Station does.
You should probably do something like
in the root-class.
Then define a new class called Station with a Name property.