ASP.net , C#: Bind a Yahoo RSS Feed to a Gridview

I want to Bind a Yahoo RSS Feed to a Gridview, then pull out the proper data (like Ttitle, Image, etc.)

So far I've got a Datasource setup and I get
rss_id and version as field names and one row of data rss_id=0 and version=2.0

My problem is that I can't pull out the indvidule items to populate the gridview.
Please modify code
public partial class rss : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = GetDataSet().Tables[0];
        GridView1.DataBind();
    }
 
    private DataSet GetDataSet()
    {
 
        DataSet ds = new DataSet("rsRSS");
        ds.ReadXml("http://rss.news.yahoo.com/rss/mostviewed");
        GridView1.DataMember = "item";
        GridView1.DataSource = ds;
        //GridView1.DataBind();
 
 
        return ds;
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridViewRow row = e.Row;
        DateTime CurrTime = DateTime.Now.Date;
 
        if (row.RowIndex >= 0) // Start looping on the first row
            if (row.RowType == DataControlRowType.DataRow)
            {
                row.Cells[0].Text = row.Cells[0].Text;
                row.Cells[1].Text = row.Cells[1].Text;
            }
    }
}

Open in new window

quest_capitalAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

rafayaliCommented:
I will go over this code in a minute. But, before I do that, I just want to go over the declarative way of doing this. Which is much easier and simpler to implement than this approach. After that we will go over your code as well. This would give us a better idea of different ways of doing the same thing in ASP .NET

i) Add XMLDATASOURCE control and configure it like this:
  Data File: Use RSS Feed URL from Yahoo
  Transform: Leave blank
  XPath: type in: rss/channel/item

ii) Add DataList control and configure it to use XMLDATASOURCE
iii) In source view, find DataList control and add this code
<itemtemplate>
<asp:hyperlink navigateUrl="<%#XPath("link")%>" text="<%#XPath("title")%>" />
</itemtemplate>

Now, run your page. THe datalist would be populated with RSS feeds. The output would be hyperlinks with text and link to follow.

Let me know if you are still interested in going over your code above. If so, I can check it up. Otherwise, the code above would fulfill most rss read requirements.
0
quest_capitalAuthor Commented:
rafayali:

I have and do retrieve most of my XML RSS like you have explained, however I need to do some data minpulation and more complitated stuff before I send it to my Grid..

Can you show me how to do it in the code behind and than place in a <itemtemplate>
0
rafayaliCommented:
Yes, here is some sample code that I took from one of the projects I did in the past. It reads xml data source at builder.com and retrieves all values through code using DOM.

Basically, I am using SelectNodes and provide an XPATH expression to retrieve all items under channel which are under rss tag. Then I iterate through the returned values and retrieve title and links and dynamically create hyperlinks.

Let me know if this helps in any way.



 Dim myXMLDOC As New XmlDocument()
        myXMLDOC.Load("http://www.builderau.com.au/feeds/features.htm")
        Dim xmlNode As XmlNode
        Dim xmllist As XmlNodeList
        xmllist = myXMLDOC.SelectNodes("rss/channel/item")
        For Each xmlNode In xmllist
            Dim titlenode As XmlNode
            Dim linknode As XmlNode
            titlenode = xmlNode.SelectSingleNode("title")
            linknode = xmlNode.SelectSingleNode("link")
            Dim myhyperlink As New HyperLink
            myhyperlink.NavigateUrl = linknode.InnerText
            myhyperlink.Text = titlenode.InnerText & "<br/><br/>"
            myhyperlink.Attributes.Add("style", "color:#336699;font-size:12px;font-family:Arial;a:hover{color:red;background-color:yellow}")
            
            placeholder1.Controls.Add(myhyperlink)
        Next
    End Sub

Open in new window

0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

quest_capitalAuthor Commented:
rafayali:

I'm a newbie at this can you show me this in C#, and than place in a <itemtemplate>
0
rafayaliCommented:
<itemtemplate> is only used if you are binding using declarative syntax; that is, syntax in the source view of the aspx page (that is mixed with html).

I have shown you an alternate programming only approach since you had mentioned you wanted to achieve more than what the functionality of the controls provided for. This way you have complete control over what is output to the client.

I am not too familiar with C#. Therefore, conversion is a bit tricky for me here. However, I will provide you with logic of each line of my code. Hopefully, then you can convert it to C#. If not, let me know I can have a friend convert it to C#. But, it should be pretty straightforward.

Here is the explanation

i) Declare an object named myXMLDOC which is an instantiation of XMLDOCUMENT class in the System.XML namespace

ii) load the URL of RSS into this object. This line WOULD STAY THE SAME IN C# i think

iii) Declare variable named xmlNode of type XMLNODE

iv) Declare variable named xmllist of type XMLNODELIST

v) In xmllist, store values that are returned after call to SelecNodes method of myXMLDOC object. myXMLDOC.SelectNodes("rss/channel/item") would probably stay as is in C#.

vi) Go over the collection stored in xmllist using For each loop of VB. You might have a similar loop in C#.

vii) Inside the loop declare variable named titleNode that is oftype xmlnode

vii) Inside the loop declare variable named linkNode which is of type xmlnode

viii) Inside the loop, store return value of xmlNode.SelectSingleNode("title") in titlenode variable

ix) Inside the loop, store return value of xmlNode.SelectSingleNode("link") in linknode variable

x) Create a new hyperlink object

xi) Use hyperlinks navigateURL property and assign the innertext of linknode to that

xii) Use hyperlinks text property and assign the innertext property of titlenode to that

xiii) Next line just adds some styling to hyperlink. You can omit that if you want

xiv) Add the control to the placeholder control. The placeholder control should be on your webform and the id of placeholder should be placeholder1. You can ofcourse change this, but the code looks for this id.

xv) Close the loop

Hopefully you can translate this into C#.

Since all CODE in ASP.NET is run in response to a trigger of some event, you can either place this code in LOAD event of Page object (Page_Load), or make this into a function (method) and call this wherever you want.

Let me know if you were able to translate it into C#. Otherwise, I will go over some C# tutorial and try to convert it for you. If anything, it would help me start up with C# :) So let me know.

All the data manipulation can be done via this code and XMLDOCUMENT class. What and how exactly do you want to manipulate the RSS feed?
Dim myXMLDOC As New XmlDocument()
 
        myXMLDOC.Load("http://www.builderau.com.au/feeds/features.htm")
        Dim xmlNode As XmlNode
        Dim xmllist As XmlNodeList
        xmllist = myXMLDOC.SelectNodes("rss/channel/item")
        For Each xmlNode In xmllist
            Dim titlenode As XmlNode
            Dim linknode As XmlNode
            titlenode = xmlNode.SelectSingleNode("title")
            linknode = xmlNode.SelectSingleNode("link")
            Dim myhyperlink As New HyperLink
            myhyperlink.NavigateUrl = linknode.InnerText
            myhyperlink.Text = titlenode.InnerText & "<br/><br/>"
            myhyperlink.Attributes.Add("style", "color:#336699;font-size:12px;font-family:Arial;a:hover{color:red;background-color:yellow}")
            
            placeholder1.Controls.Add(myhyperlink)
        Next
    End Sub

Open in new window

0
rafayaliCommented:
I checked your code on my visual studio 2008.

Modify as follows:

 protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = GetDataSet().Tables[3];
        GridView1.DataBind();
    }

Instead of tables[0], get tables[3]
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rafayaliCommented:
What is happening here, I believe, is that dataset's readxml method is creating a datatable for each level of nesting in the RSS XML file. Therefore, if you want to experiemnt further change tables(3) to tables(4),tables(5), tables(6) and see that the result varies. Therefore, try experimenting with it. I have come to the conclusion that this is what is happening in this case because clearly there are more than one data table even though nothing of this sort was specified in the code.

0
rafayaliCommented:
And, to show only a particular column such as only title column in the gridview use this code inside gridview

<Columns>
        <asp:TemplateField>
       
        <ItemTemplate>
              <%# DataBinder.Eval(Container.DataItem, "title") %>
        </ItemTemplate></asp:TemplateField></Columns>

This should be between <asp:gridview></asp:gridview tags>

To further enhance this you can also place this in the itemtemplate instead

 <ItemTemplate>
       
       <asp:HyperLink ID="HyperLink1" NavigateUrl=<%#DataBinder.Eval(Container.DataItem,"link") %> runat="server"><%#DataBinder.Eval(Container.DataItem,"title") %>
       </asp:HyperLink>
       </ItemTemplate>

0
rafayaliCommented:
Let me know if this helped or you needed some other thing?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.