Search code examples
c#xmlwindows-phone-8.1rssrss-reader

How to read the attribute of an element xml in C# Windows Phone?


I developing an app that can read rss, I set a class like that

public class Item
{
    [XmlElement("title")]
    public string title { get; set; }
    [XmlElement("description")]
    public string description { get; set; }
    [XmlElement("enclosure")]
    public string enclosure { get; set; }
    [XmlElement("pubDate")]
    public string pubDate { get; set; }
    [XmlElement("link")]
    public string link { get; set; }
}

Howerver, the item returns that

<item>
<title>
Colombia 2-1 Paraguay: James Rodriguez and Carlos Bacca score as Jose Pekerman's side reach Copa America quarter-finals
</title>
<link>
http://www.dailymail.co.uk/sport/football/article-3630657/Colombia-2-1-Paraguay-James-Rodriguez-Carlos-Bacca-score-Jose-Pekerman-s-reach-Copa-America-quarter-finals.html?ITO=1490&ns_mchannel=rss&ns_campaign=1490
</link>
<description>
James Rodriguez scored a goal and set up another as Colombia became the first team to clinch a place in the Copa America quarter-finals. The Real Madrid provided the assist for Carlos Bacca's opener.
</description>
<enclosure url="http://i.dailymail.co.uk/i/pix/2016/06/08/05/350A4D8200000578-0-image-a-63_1465360921756.jpg" type="image/jpeg" length="84507" />
<pubDate>Wed, 08 Jun 2016 06:32:45 +0100</pubDate>
<guid>
http://www.dailymail.co.uk/sport/football/article-3630657/Colombia-2-1-Paraguay-James-Rodriguez-Carlos-Bacca-score-Jose-Pekerman-s-reach-Copa-America-quarter-finals.html?ITO=1490&ns_mchannel=rss&ns_campaign=1490
</guid>
</item>

So, it is clearly that the "enclosure" element return empty string, so how to read the "url" attribute of this "enclosure" tag by giving the annotation like above class, please help me!


Solution

  • You have to write separate class for enclosure

         public class Item
            {
                [XmlElement("title")]
                public string title { get; set; }
                [XmlElement("description")]
                public string description { get; set; }
                [XmlElement("enclosure")]
                public Enclosure enclosure { get; set; }
                [XmlElement("pubDate")]
                public string pubDate { get; set; }
                [XmlElement("link")]
                public string link { get; set; }
            }
    
        public class Enclosure 
        {
            [XmlAttribute("url")]
            public string Url { get; set; }
        //if enclosure has any child elements it comes under XmlElement like this
        // [XmlElement("enclosurechildelement")]
        // public string enclosurechildelement { get; set; }
    
    
        }