我正在学习Servicestack.Text库,因为它具有一些最好的功能。我正在尝试将 XML 反序列化为我的 DTO 之一,如下所示;
C# 代码: [此处带有控制台应用程序的相关代码]
class Program
{
static void Main(string[] args)
{
string str = "http://static.cricinfo.com/rss/livescores.xml";
WebClient w = new WebClient();
string xml = w.DownloadString(str);
Response rss = xml.FromXml<Response>();
foreach (var item in rss.rss.Channel.item)
{
Console.WriteLine(item.title);
}
Console.Read();
}
}
您可以在str
[Given in the program] 处浏览 XML 文件。我已经为反序列化准备了 DTO。它们如下:
public class Response
{
public RSS rss { get; set; }
}
public class RSS
{
public string Version { get; set; }
public ChannelClass Channel { get; set; }
}
public class ChannelClass
{
public string title { get; set; }
public string ttl { get; set; }
public string description { get; set; }
public string link { get; set; }
public string copyright { get; set; }
public string language { get; set; }
public string pubDate { get; set; }
public List<ItemClass> item { get; set; }
}
public class ItemClass
{
public string title { get; set; }
public string link { get; set; }
public string description { get; set; }
public string guid { get; set; }
}
当我运行程序时,我得到一个异常,如下所示:
因此,要更改Element
和namespace
,我做了以下解决方法:
我把DataContractAttribute
我的Response
班级如下:
[DataContract(Namespace = "")]
public class Response
{
public RSS rss { get; set; }
}
Element
我通过在反序列化之前添加以下两行来更改名称如下
//To change rss Element to Response as in Exception
xml = xml.Replace("<rss version=\"2.0\">","<Response>");
//For closing tag
xml = xml.Replace("</rss>","</Response>");
但是,它在 foreach 循环中给出了另一个例外,因为反序列化的rss
对象是null
. 那么,我应该如何使用正确的方式反序列化它Servicestack.Text
?
笔记 :
我很清楚如何用其他库反序列化,我只想用 ServiceStack 来做。