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.

summary ❘ 953<br />

In this case, the first instance of the element is overwritten with the value of Bill Evjen, king<br />

of Denmark using the SetValue() method of the Element() object. After the SetValue() is called <strong>and</strong> the<br />

value is applied to the XML document, the value is then retrieved using the same approach as before. When<br />

you run this bit of code, you can indeed see that the value of the first element has been changed.<br />

Another way to change the document (by adding items to it in this example) is to create the elements you<br />

want as XElement objects <strong>and</strong> then add them to the document:<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 />

XElement xe = new XElement("PERSONA",<br />

"Bill Evjen, king of Denmark");<br />

xdoc.Element("PLAY").Element("PERSONAE").Add(xe);<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 />

}<br />

}<br />

}<br />

Console.ReadLine();<br />

code download ConsoleApplication1.sln<br />

In this case, an XElement document is created called xe. The construction of xe will give you the following<br />

XML output:<br />

Bill Evjen, king of Denmark<br />

Then using the Element().Add() method from the XDocument object, you are able to add the created element:<br />

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

Now when you query all the players, you will find that instead of 26 as before, you now have 27 with the<br />

new one at the bottom of the list. In addition to Add(), you can also use AddFirst(), which will do what it<br />

says — add it to the beginning of the list instead of the end (which is the default).<br />

summary<br />

In this chapter, you explored many aspects of the System.Xml namespace of the .<strong>NET</strong> Framework. You<br />

looked at how to read <strong>and</strong> write XML documents using the very fast XmlReader- <strong>and</strong> XmlWriter-based<br />

classes. You looked at how the DOM is implemented in .<strong>NET</strong> <strong>and</strong> how to use the power of DOM. You saw<br />

that XML <strong>and</strong> ADO.<strong>NET</strong> are indeed very closely related. A DataSet <strong>and</strong> an XML document are just two<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!