我正在尝试将XML文件反序列化为类。 XML文件如下所示:
<?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>
我要将其反序列化的类是:
[XmlRootAttribute("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; }
}
}
我尝试反序列化XML文件
XmlSerializer deserializer = new XmlSerializer(typeof(List<SnowPark>));
TextReader textReader = new StreamReader(@"file.xml");
List<SnowPark> parks;
parkss = (List<SnowPark>)deserializer.Deserialize(textReader);
textReader.Close();
但是我得到一个例外:
There is an error in XML document (2, 2).
和内部异常:
<locations xmlns=''> was not expected.
到目前为止,没有运气找到解决方案。帮助赞赏。
答案 0 :(得分:4)
XmlRootAttribute不适用,因为您正在序列化列表,而不是单个项目;这也意味着你的XML比需要的还要多一层。
IMO,您最简单的选择是:
[XmlRoot("locations")]
public class Locations
{
[XmlElement("location")]
public List<SnowPark> Parks {get;set;}
}
并反序列化Locations对象,使用typeof(Locations)
初始化XmlSerializer