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.

948 ❘ ChaPTer 33 mAnipulAtinG xml<br />

}<br />

}<br />

}<br />

new XElement("Country", "USA")));<br />

Console.WriteLine(xe.ToString());<br />

Console.ReadLine();<br />

Here, the attribute MyAttribute with a value of MyAttributeValue is added to the root element of the<br />

XML document, producing the results shown in Figure 33-11.<br />

figure 33-11<br />

using linq To query Xml doCumenTs<br />

Now that you can get your XML documents into an XDocument object <strong>and</strong> work with the various parts of<br />

this document, you can also use LINQ to XML to query your XML documents <strong>and</strong> work with the results.<br />

querying static Xml documents<br />

You will notice that querying a static XML document using LINQ to XML takes almost no work at all. The<br />

following example makes use of the hamlet.xml file <strong>and</strong> queries to get all the players (actors) that appear in<br />

the play. Each of these players is defined in the XML document with the element:<br />

using System;<br />

using System.Linq;<br />

using System.Xml.Linq;<br />

namespace ConsoleApplication1<br />

{<br />

class Class1<br />

{<br />

static void Main(string[] args)<br />

{<br />

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

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

select people.Value;<br />

Console.WriteLine("{0} Players Found", query.Count());<br />

Console.WriteLine();<br />

foreach (var item in query)<br />

{<br />

Console.WriteLine(item);<br />

}<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!