Saturday, 20 May 2017

XML Writer

XmlWriter is a simple fast forward only non-chached xml writer, in short it's useful to only write xml.

using System;
using System.IO;
using System.Xml;

class Program
{
    static void Main(string[] args)
    {
        using (var sw = new StringWriter())
        {
            using (var writer = XmlWriter.Create(sw,
                    new XmlWriterSettings() { Indent = true }))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("People");

                writer.WriteStartElement("Person");
                writer.WriteAttributeString("FirstName""Pawel");
                writer.WriteAttributeString("LastName""Chooch");

                writer.WriteStartElement("ContactDetails");
                writer.WriteElementString("EmailAddress""fake@yahoo.com");

                writer.WriteEndElement(); //contactDetails
                writer.WriteEndElement(); //Person

                writer.WriteStartElement("Person");
                writer.WriteAttributeString("FirstName""Tomek");
                writer.WriteAttributeString("LastName""Chooch");

                writer.Flush();
            }
            Console.WriteLine(sw.ToString());
        }
    }
}

notice the WriteEndElement(); it's used to close the previous xml node, if we didn't do this then the following person would have been a child of Contact details, with them in place our output is



And if it was omitted.



Notice the location of the second person we added tomek.