15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

950 ❘ ChaPTer 33 mAnipulAtinG xml<br />

static void Main()<br />

{<br />

XDocument xdoc =<br />

XDocument.Load(@"http://geekswithblogs.net/evjen/Rss.aspx");<br />

var query = from rssFeed in xdoc.Descendants("channel")<br />

select new<br />

{<br />

Title = rssFeed.Element("title").Value,<br />

Description = rssFeed.Element("description").Value,<br />

Link = rssFeed.Element("link").Value,<br />

};<br />

foreach (var item in query)<br />

{<br />

Console.WriteLine("TITLE: " + item.Title);<br />

Console.WriteLine("DESCRIPTION: " + item.Description);<br />

Console.WriteLine("LINK: " + item.Link);<br />

}<br />

Console.WriteLine();<br />

var queryPosts = from myPosts in xdoc.Descendants("item")<br />

select new<br />

{<br />

Title = myPosts.Element("title").Value,<br />

Published =<br />

DateTime.Parse(<br />

myPosts.Element("pubDate").Value),<br />

Description =<br />

myPosts.Element("description").Value,<br />

Url = myPosts.Element("link").Value,<br />

Comments = myPosts.Element("comments").Value<br />

};<br />

foreach (var item in queryPosts)<br />

{<br />

Console.WriteLine(item.Title);<br />

}<br />

}<br />

}<br />

}<br />

Console.ReadLine();<br />

code download ConsoleApplication1.sln<br />

Looking at this code, you can see that the Load() method of the XDocument object points to a URL where<br />

the XML is retrieved. The first query pulls out all the main subelements of the element in the<br />

feed <strong>and</strong> creates new objects called Title, Description, <strong>and</strong> Link to get at the values of these subelements.<br />

From there, a foreach statement is run to iterate through all the items found in this query. The results are<br />

as follows:<br />

TITLE: Bill Evjen's Blog<br />

DESCRIPTION: Code, Life <strong>and</strong> Community<br />

LINK: http://geekswithblogs.net/evjen/Default.aspx<br />

The second query works through all the elements <strong>and</strong> the various subelements it finds (these are<br />

all the blog entries found in the blog). Though a lot of the items found are rolled up into properties, in the<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!