XML Deserialization inner exception
I am trying to deserialize an XML file to a class. The XML file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<locations>
<location id="0">
<name>park</name>
<temperature>5</temperature>
<wind>26</wind>
<weather_text_SI>sunny</weather_text_SI>
<visibility></visibility>
<latitude>46.4527</latitude>
<longitude>15.334</longitude>
<elevation>1517</elevation>
</location>
</locations>
The class that I want to deserialize it to is:
[XmlRoot开发者_如何学CAttribute("locations")]
public class SnowPark
{
public SnowPark()
{
}
private int id;
[XmlAttribute("id")]
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
[XmlElement("name")]
public string Name
{
get { return name; }
set { name = value; }
}
private int temperature;
[XmlElement("temperature")]
public int Temperature
{
get { return temperature; }
set { temperature = value; }
}
private int wind;
[XmlElement("wind")]
public int Wind
{
get { return wind; }
set { wind = value; }
}
private string weatherText;
[XmlElement("weather_text_SI")]
public string WeatherText
{
get { return weatherText; }
set { weatherText = value; }
}
private double latitude;
[XmlElement("latitude")]
public double Latitude
{
get { return latitude; }
set { latitude = value; }
}
private double longitude;
[XmlElement("longitude")]
public double Longitude
{
get { return longitude; }
set { longitude = value; }
}
private int elevation;
[XmlElement("elevation")]
public int Elevation
{
get { return elevation; }
set { elevation = value; }
}
}
I try to deserialize the XML file
XmlSerializer deserializer = new XmlSerializer(typeof(List<SnowPark>));
TextReader textReader = new StreamReader(@"file.xml");
List<SnowPark> parks;
parkss = (List<SnowPark>)deserializer.Deserialize(textReader);
textReader.Close();
However I get an exception:
There is an error in XML document (2, 2).
and an inner exception:
<locations xmlns=''> was not expected.
No luck finding the solution so far. Help appreciated.
The XmlRootAttribute doesn't apply since you are serialising a list of then, not an individual item; this also means your XML is one layer further-out than needed.
IMO, your easiest option here is:
[XmlRoot("locations")]
public class Locations
{
[XmlElement("location")]
public List<SnowPark> Parks {get;set;}
}
and deserialize a Locations object, using typeof(Locations)
to initialisers the XmlSerializer
精彩评论