0

我正在尝试反序列化位于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();

    }

关于如何反序列化这个休息服务的任何想法?谢谢..

4

1 回答 1

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
                );
            }
        }
    }
}
于 2012-05-21T18:54:20.873 回答