: C# 2008 Programmer

Creating XML Trees

Creating XML Trees

To create an XML document tree in memory, use the XDocument object, which represents an XML document. To create an XML element, use the XElement class; for attributes, use the XAttribute class. The following code shows how to build an XML document using these objects:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace LINQtoXML {
class Program {
static void Main(string[] args) {
XDocument library = new XDocument(
new XElement("Library",
new XElement("Book",
new XAttribute("published", "NYP"),
new XElement("Title", "C# 2008 Programmers' Reference"),
new XElement("Publisher", "Wrox")
),
new XElement("Book",
new XAttribute("published", "Published"),
new XElement("Title", "Professional Windows Vista " +
"Gadgets Programming"),
new XElement("Publisher", "Wrox")
),
new XElement("Book",
new XAttribute("published", "Published"),
new XElement("Title", "ASP.NET 2.0 - A Developer's " +
"Notebook"),
new XElement("Publisher", "O'Reilly")
),
new XElement("Book",
new XAttribute("published", "Published"),
new XElement("Title", ".NET 2.0 Networking Projects"),
new XElement("Publisher", "Apress")
),
new XElement("Book",
new XAttribute("published", "Published"),
new XElement("Title", "Windows XP Unwired"),
new XElement("Publisher", "O'Reilly")
)
)
);
}
}
}

The indentation gives you an overall visualization of the document structure.

To save the XML document to file, use the Save() method:

library.Save("Books.xml");

To print out the XML document as a string, use the ToString() method:

Console.WriteLine(library.ToString());

When printed, the XML document looks like this:

<Library>
<Book published="NYP">
<Title>C# 2008 Programmers' Reference</Title>
<Publisher>Wrox</Publisher>
</Book>
<Book published="Published">
<Title>Professional Windows Vista Gadgets Programming</Title>
<Publisher>Wrox</Publisher>
</Book>
<Book published="Published">
<Title>ASP.NET 2.0 - A Developer's Notebook</Title>
<Publisher>O'Reilly</Publisher>
</Book>
<Book published="Published">
<Title>.NET 2.0 Networking Projects</Title>
<Publisher>Apress</Publisher>
</Book>
<Book published="Published">
<Title>Windows XP Unwired</Title>
<Publisher>O'Reilly</Publisher>
</Book>
</Library>

To load an XML document into the XDocument object, use the Load() method:

XDocument LibraryBooks = new XDocument();
LibraryBooks = XDocument.Load("Books.xml");


: 0.033. /Cache: 0 / 0