15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

More Query Techniques for XMl Documents ❘ 951<br />

foreach loop, only the Title property is used. You will see something similar to the following results from<br />

this query:<br />

AJAX Control Toolkit Controls Grayed Out-HOW TO FIX<br />

Welcome .<strong>NET</strong> 4.0!<br />

Visual Studio<br />

IIS 7.0 Rocks the House!<br />

Word Issue-Couldn't Select Text<br />

Microsoft Releases XML Schema Designer CTP1<br />

Silverlight Book<br />

Microsoft Tafiti as a beta<br />

ReSharper on Visual Studio<br />

Windows Vista Updates for Performance <strong>and</strong> Reliability Issues<br />

First Review of Professional XML<br />

Go to MIX07 for free!<br />

Microsoft Surface <strong>and</strong> the Future of Home Computing<br />

Alas my friends-I'm *not* TechEd bound<br />

more query TeChniques for Xml doCumenTs<br />

If you have been working with the XML document hamlet.xml, you will notice that it is quite large. So far,<br />

you’ve seen a couple of ways to query into the XML document in this chapter, but this next section takes a<br />

look at reading <strong>and</strong> writing to the XML document.<br />

reading from an Xml document<br />

Earlier you saw just how easy it was to query into an XML document using the LINQ query statements, as<br />

shown here:<br />

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

select people.Value;<br />

This query returned all the players that were found in the document. Using the Element() method of the<br />

XDocument object, you can also get at specific values of the XML document that you are working with. For<br />

instance, the following XML fragment shows you how the title is represented in the hamlet.xml document:<br />

<br />

<br />

The Tragedy of Hamlet, Prince of Denmark<br />

<br />

<br />

As you can see, the element is a nested element of the element. You can easily get at the<br />

title by using the following bit of code in your console application:<br />

XDocument xdoc = XDocument.Load(@"C:\hamlet.xml");<br />

Console.WriteLine(xdoc.Element("PLAY").Element("TITLE").Value);<br />

This bit of code will write out the title, The Tragedy of Hamlet, Prince of Denmark, to the console<br />

screen. In the code, you were able to work down the hierarchy of the XML document by using two<br />

Element() method calls — first calling the element <strong>and</strong> then the element found nested<br />

within the element.<br />

Looking more at the hamlet.xml document, you will see a large list of players that are defined with the use<br />

of the element:<br />

<br />

<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!