Creating XML Documents

Because XML documents are structured text documents, you can create them using a text editor and process them using string manipulation functions. To paraphrase David Platt, you can also have an appendectomy through your mouth, but it takes longer and hurts more.

To make the job easier, .NET implements a collection of classes and utilities that provide XML functionality, including the streaming XML APIs (which support XmlReader and XmlWriter), and another set of XML APIs that use the XML Document Object Model (DOM).

In Chapter 13, we used a list of customers in our examples. We will use the same customer list in this chapter, starting with Example 14-1, in which we'll write the list of customers to an XML document.

Example 14-1. Creating an XML document

using System; using System.Collections.Generic; using System.Xml; namespace Programming_CSharp { // Simple customer class public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } // Overrides the Object.ToString( ) to provide a // string representation of the object properties. public override string ToString( ) { return string.Format("{0} {1}\nEmail: {2}", FirstName, LastName, EmailAddress); } } // Main program public class Tester { static void Main( ) { List<Customer> customers = CreateCustomerList( ); XmlDocument customerXml = new XmlDocument( ); XmlElement rootElem = customerXml.CreateElement("Customers"); customerXml.AppendChild(rootElem); ...

Get Programming C# 3.0, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.