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.

XML ❘ ChaPTer 33 mAnipulAtinG xml<br />

Xelement<br />

One object that you will work with frequently is the XElement object. With XElement objects, you can<br />

easily create single-element objects that are XML documents themselves, as well as fragments of XML. For<br />

instance, here is an example of writing an XML element with a corresponding value:<br />

XElement xe = new XElement("Company", "Lipper");<br />

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

In the creation of a XElement object, you can define the name of the element as well as the value used<br />

in the element. In this case, the name of the element will be , <strong>and</strong> the value of the <br />

element will be Lipper. Running this in a console application with a System.Xml.Linq reference produces<br />

the following result:<br />

Lipper<br />

You can create an even more complete XML document using multiple XElement objects, as illustrated in the<br />

following example:<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 />

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

new XElement("CompanyName", "Lipper"),<br />

new XElement("CompanyAddress",<br />

new XElement("Address", "123 Main Street"),<br />

new XElement("City", "St. Louis"),<br />

new XElement("State", "MO"),<br />

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

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

}<br />

}<br />

}<br />

Console.ReadLine();<br />

code download ConsoleApplication1.sln<br />

Running this application produces the results illustrated in Figure 33-7.<br />

figure 33-7<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!