Parsing XML from string C#

2019-08-15 05:23发布

问题:

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:

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);
}


回答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.



回答3:

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