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.

946 ❘ ChaPTer 33 mAnipulAtinG xml<br />

{<br />

class Class1<br />

{<br />

static void Main()<br />

{<br />

XNamespace ns1 = "http://www.lipperweb.com/ns/root";<br />

XNamespace ns2 = "http://www.lipperweb.com/ns/sub";<br />

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

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

new XElement(ns2 + "CompanyAddress",<br />

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

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

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

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

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

}<br />

}<br />

}<br />

Console.ReadLine();<br />

code download ConsoleApplication1.sln<br />

This produces the results shown in Figure 33-9.<br />

figure 33-9<br />

In this case, you can see that the subnamespace was applied to everything you specified except for the<br />

, , , <strong>and</strong> the elements because they inherit from their parent,<br />

, which has the namespace declaration.<br />

XComment<br />

The XComment object allows you to easily add XML comments to your XML documents. The following<br />

example shows the addition of a comment to the top of 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(string[] args)<br />

{<br />

XDocument xdoc = new XDocument();<br />

XComment xc = new XComment("Here is a comment.");<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!