I am learning Servicestack.Text Library as it has some of the best features.I am trying to deserialize XML into one of my DTOs as below;
C# Code:[Relevant Code with Console Application Here]
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();
}
}
You can go through the XML file at str
[Given in the program]. I have prepared DTOs for the deserialization. They are as below:
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; }
}
When I run the program, I get an exception as shown below:
So, to change the Element
and the namespace
, I did following workaround:
I put the DataContractAttribute
on my Response
class as below:
[DataContract(Namespace = "")]
public class Response
{
public RSS rss { get; set; }
}
I changed the Element
name as below by adding following two lines just before deserializing
//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>");
But, it gave another exception on the foreach loop as the deserialized rss
object was null
. So, how should I deserialize it in a proper way using Servicestack.Text
?
Note :
I know well how to deserialize with other libraries, I want to do it with ServiceStack only.
servicestack
? – Jourdain