03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Writing XML Data ❘ 543<br />

// Save the document in a file.<br />

using (XmlTextWriter writer = new XmlTextWriter(fileTextBox.Text, null))<br />

{<br />

// Make it pretty.<br />

writer.Formatting = Formatting.Indented;<br />

}<br />

document.WriteTo(writer);<br />

}<br />

// Display the file.<br />

resultTextBox.Text = File.ReadAllText(fileTextBox.Text);<br />

The code first creates an XDocument object to represent the XML code.<br />

Next, it creates an XElement object to represent the file’s Students element and uses the document’s<br />

Add method to add it to the document’s child collection.<br />

The code creates another XElement to represent the Description element and adds it to the<br />

Students element. It then adds a new XCdata object to hold the Description’s data.<br />

The rest of the code follows a similar pattern, creating new objects and adding them to the child<br />

collections of the objects that should contain them.<br />

After it finishes building the document, the program creates an XmlTextWriter much as<br />

the FormatXml example program did. It sets the writer’s Formatting property and then uses the<br />

document object’s WriteTo method to make the document write its XML code into a file.<br />

The program finishes by displaying the resulting XML file.<br />

Another DOM<br />

The WriteDom example program uses System.Xml.Linq classes to build an XML<br />

document object model. The System.Xml namespace contains other versions of<br />

similar classes. For example, it includes XmlDocument, XmlElement, XmlComment,<br />

and other classes. Building an XML document object model with those classes is<br />

similar to building one with the System.Xml.Linq classes, with some minor differences.<br />

Building objects models is easier with the newer System.Xml.Linq classes,<br />

however, so you should probably use them.<br />

Two of the most important classes for manipulating the DOM are XDocument and XElement.<br />

The XDocument class’s most useful properties are Declaration, which gets or sets the document’s<br />

XML declaration, and Root, which returns the document’s root element. The following table lists<br />

the XDocument class’s most useful methods.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!