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.

952 ❘ ChaPTer 33 mAnipulAtinG xml<br />

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

<br />

<br />

Dramatis Personae<br />

CLAUDIUS, king of Denmark.<br />

HAMLET, son to the late king,<br />

<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 />

<br />

<br />

<br />

Now look at this <strong>C#</strong> query:<br />

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

Console.WriteLine(<br />

xdoc.Element("PLAY").Element("PERSONAE").Element("PERSONA").Value);<br />

This bit of code starts at , works down to the element, <strong>and</strong> then makes use of the<br />

element. However, using this will produce the following results:<br />

CLAUDIUS, king of Denmark<br />

The reason for this is that although there is a collection of elements, you are dealing only with<br />

the first one that is encountered using the Element().Value call.<br />

Writing to an Xml document<br />

In addition to reading from an XML document, you can write to the document just as easily. For instance, if<br />

you wanted to change the name of the first player of the Hamlet play file, you could use the following code:<br />

using System;<br />

using System.Linq;<br />

using System.Xml.Linq;<br />

namespace ConsoleApplication1<br />

{<br />

class Class1<br />

{<br />

static void Main()<br />

{<br />

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

xdoc.Element("PLAY").Element("PERSONAE").<br />

Element("PERSONA").SetValue("Bill Evjen, king of Denmark");<br />

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

Element("PERSONAE").Element("PERSONA").Value);<br />

}<br />

}<br />

}<br />

Console.ReadLine();<br />

code download ConsoleApplication1.sln<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!