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?

1

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

Would I still need a Stations class?
You need a class to hold the Stations property. As long as it's decorated with the XmlRoot attribute I think it should work.
stations = (Station[])serializer.Deserialize(reader); ^getting an error on this line: Unable to cast object of type Station to Station[]
You should only have to deserialize the root-object (and let the serializer figure out the rest). See the example in this question: stackoverflow.com/questions/364253/…
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.