Skip to Content
.NET & XML
book

.NET & XML

by Niel M. Bornstein
November 2003
Intermediate to advanced
476 pages
14h 38m
English
O'Reilly Media, Inc.
Content preview from .NET & XML

Using the XmlWriter

XmlWriter contains methods to write any type of XML node to its output Stream. There is just one subclass in the .NET Framework, XmlTextWriter, which will handle most of your XML output needs.

Example 3-3 shows a short program that writes data to an XmlTextWriter.

Example 3-3. Program to write XML with XmlTextWriter
using System; using System.IO; using System.Text; using System.Xml; public class WriteXml { public static void Main(string [ ] args) { // Create the XmlWriter XmlTextWriter writer = new XmlTextWriter(Console.Out); // Set the formatting to something nice writer.Formatting = Formatting.Indented; // Write the XML declaration writer.WriteStartDocument(true); // Write a comment writer.WriteComment("the first element follows."); // Start the root element writer.WriteStartElement("root"); // Write an attribute writer.WriteAttributeString("id","_1"); // Write another attribute writer.WriteStartAttribute"name", "foo"); writer.WriteString("bar"); writer.WriteEndAttribute( ); // Write another element writer.WriteElementString("element1","some characters"); writer.WriteStartElement("cdataElement"); writer.WriteAttributeString("date",DateTime.Now.ToString( )); writer.WriteCData("<this contains some characters XML wouldn't like & would choke on"); writer.WriteString("<this contains some characters XML wouldn't like & so the XmlWriter replaces them"); writer.WriteEndElement( ); // Write an empty element writer.WriteStartElement("emptyElement"); writer.WriteEndElement( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Applied XML Programming for Microsoft® .NET

Applied XML Programming for Microsoft® .NET

Dino Esposito
XML Hacks

XML Hacks

Michael Fitzgerald

Publisher Resources

ISBN: 0596003978Supplemental ContentErrata