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.

Using linQ to Query XMl Documents ❘ 949<br />

}<br />

}<br />

}<br />

Console.ReadLine();<br />

code download ConsoleApplication1.sln<br />

In this case, an XDocument object loads up a physical XML file (hamlet.xml) <strong>and</strong> then performs a LINQ<br />

query over the contents of the document:<br />

var query = from people in xdoc.Descendants("PERSONA")<br />

select people.Value;<br />

The people object is a representation of all the elements found in the document. Then the<br />

select statement gets at the values of these elements. From there, a Console .WriteLine() method is<br />

used to write out a count of all the players found using query.Count(). Next, each of the items is written<br />

to the screen in a foreach loop. The results you should see are presented here:<br />

26 Players Found<br />

CLAUDIUS, king of Denmark.<br />

HAMLET, son to the late king, <strong>and</strong> nephew to the present king.<br />

POLONIUS, lord chamberlain.<br />

HORATIO, friend to Hamlet.<br />

LAERTES, son to Polonius.<br />

LUCIANUS, nephew to the king.<br />

VOLTIMAND<br />

CORNELIUS<br />

ROSENCRANTZ<br />

GUILDENSTERN<br />

OSRIC<br />

A Gentleman<br />

A Priest.<br />

MARCELLUS<br />

BERNARDO<br />

FRANCISCO, a soldier.<br />

REYNALDO, servant to Polonius.<br />

Players.<br />

Two Clowns, grave-diggers.<br />

FORTINBRAS, prince of Norway.<br />

A Captain.<br />

English Ambassadors.<br />

GERTRUDE, queen of Denmark, <strong>and</strong> mother to Hamlet.<br />

OPHELIA, daughter to Polonius.<br />

Lords, Ladies, Officers, Soldiers, Sailors, Messengers, <strong>and</strong> other Attendants.<br />

Ghost of Hamlet's Father.<br />

querying dynamic Xml documents<br />

A lot of dynamic XML documents are available on the Internet these days. You will find blog feeds,<br />

podcast feeds, <strong>and</strong> more that provide an XML document by sending a request to a specific URL endpoint.<br />

These feeds can be viewed either in the browser, through an RSS-aggregator, or as pure XML. This example<br />

shows you how to work with an RSS feed directly from your code.<br />

using System;<br />

using System.Linq;<br />

using System.Xml.Linq;<br />

namespace ConsoleApplication1<br />

{<br />

class Class1<br />

{<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!