我正在尝试反序列化位于http://ws.geonames.org/countryInfo?lang=it&country=DE的rest uri并继续收到错误(XML文档(1,1)中存在错误)。将http://ws.geonames.org/countryInfo?lang=it&country=DE插入浏览器即可看到结果。
我有一个班级
public class Country
{
public string CountryName {get;set;}
public string CountryCode {get;set;}
}
我的控制台应用程序中的方法如下:
static void DeserializeTheXML()
{
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "countryName";
xRoot.IsNullable = true;
XmlSerializer ser = new XmlSerializer(typeof(Country), xRoot);
XmlReader xRdr = XmlReader.Create(new StringReader("http://ws.geonames.org/countryInfo?lang=it&country=DE"));
Country tvd = new Country();
tvd = (Country)ser.Deserialize(xRdr);
Console.WriteLine("Country Name = " + tvd.CountryName);
Console.ReadKey();
}
有关如何反序列化此休息服务的任何想法?感谢..
答案 0 :(得分:2)
要使序列化成功运行,您需要使用正确的序列化属性修饰对象或使用XmlAttributeOverrides构造函数。另外,请不要忘记XML区分大小写,并且您的对象必须反映您要反序列化的XML结构:
public class GeoNames
{
[XmlElement("country")]
public Country[] Countries { get; set; }
}
public class Country
{
[XmlElement("countryName")]
public string CountryName { get; set; }
[XmlElement("countryCode")]
public string CountryCode { get; set; }
}
class Program
{
static void Main()
{
var url = "http://ws.geonames.org/countryInfo?lang=it&country=DE";
var serializer = new XmlSerializer(typeof(GeoNames), new XmlRootAttribute("geonames"));
using (var client = new WebClient())
using (var stream = client.OpenRead(url))
{
var geoNames = (GeoNames)serializer.Deserialize(stream);
foreach (var country in geoNames.Countries)
{
Console.WriteLine(
"code: {0}, name: {1}",
country.CountryCode,
country.CountryName
);
}
}
}
}