• Create XML using XMLWriter

    Posted on April 8, 2013 by in Dotnet Tips & Tricks, Tips & Tricks

    XMLWriter is used to create xml data. It is a fast, non-cached, forward-only means of generating streams. Programmers should stop using StringBuilder to create xml documents, as it is error prone and the xml may not be well formed.

    In our example,  I will explain how to create a wellformed XML from a list of products by writing a simple console application that would populate a sample products list and then writes to a xml document using XMLWriter.

    using System;
    using System.Collections.Generic;
    using System.Xml;
    
    namespace TipsConsoleApp
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                //prepare a sample product list
                List<Product> products = new List<Product>();
                Product product = new Product();
                product.ProductID = 706;
                product.ProductName = "HL Road Frame - Red, 58";
                product.ProductSubCategoryName = "Road Bikes";
                products.Add(product);
    
                product = new Product();
                product.ProductID = 749;
                product.ProductName = "Road-150 Red, 62";
                product.ProductSubCategoryName = "Road Bikes";
                products.Add(product);
    
                product = new Product();
                product.ProductID = 953;
                product.ProductName = "Touring-2000 Blue, 60";
                product.ProductSubCategoryName = "Touring Bikes";
                products.Add(product);
    
                //create a xml document from the list
                WriteXML(products);
            }
    
            public static void WriteXML(List<Product> products)
            {
                //Creates a new System.Xml.XmlWriter instance using the specified filename.
                //The file to which you want to write. The System.Xml.XmlWriter creates a file
                //at the specified path.  The outputFileName must be a file system path.
                using (XmlWriter writer = XmlWriter.Create(@"C:\Temp\Products.xml"))
                {
                    //writes the XML declaration with the version "1.0".
                    //<?xml version="1.0" encoding="UTF-8"?>
                    writer.WriteStartDocument();
    
                    //writes out a start tag with the specified local name.
                    //<Products>
                    writer.WriteStartElement("Products");
    
                    foreach (Product product in products)
                    {
                        //writes out a start tag with the specified name.
                        //<Product>
                        writer.WriteStartElement("Product");
    
                        // writes out the attribute with the specified name and value.
                        // ID="{value}"
                        writer.WriteAttributeString("ID", product.ProductID.ToString());
    
                        //writes an element with the specified name and value.
                        //<Name>{value}</Name>
                        writer.WriteElementString("Name", product.ProductName);
    
                        //this is another way of writing an element. 
                        writer.WriteStartElement("ProductSubCategoryName");
                        writer.WriteValue(product.ProductSubCategoryName);
                        writer.WriteEndElement();
    
                        //writes end element tag
                        //</Product>
                        writer.WriteEndElement();
                    }
                    //writes end element tag
                    //</Products>
                    writer.WriteEndElement();
    
                    //closes any open elements or attributes and puts the writer back in the Start state.
                    writer.WriteEndDocument();
                }
            }
        }
    }
    

    Run the application and you would see an xml file (Products.xml) is created in the C:\Temp folder 

    Create XML using XMLWriter

    Create XML using XMLWriter

    Be Sociable, Share!
      Post Tagged with , ,

    Written by

    Software architect with over 10 years of proven experience in designing & developing n-tier and web based software applications, for Finance, Telecommunication, Manufacturing, Internet and other Commercial industries. He believes that success depends on one's ability to integrate multiple technologies to solve a simple as well as complicated problem.

    View all articles by

    Email : [email protected]

    Leave a Reply