More articles

Creating An XML Document in ASP.NET

Written by
Filed under
Published on
Modified on

There are various different approaches to XML document creation in .NET. There is no right or wrong way really, it just depends on the situation and what you're more comfortable with. You need to generate an XML file in an hour? Then have it and glue together your data manually in XML and save it into a file with a .xml extension. You need a reusable and scalable XML generation tool? Then you can use a more programmatic approach to the problem. Lucky for us the .NET Framework can help us out with whatever approach we want to take.

1. Concatenate XML Using StringBuilder

The simplest way to create an XML file is to just simply make one yourself using strings. You save time, because you don't have to worry about knowing how the XML namespace and classes work and the little subtle nuances that go with it, but it's also time consuming, because formatting and error checking is left up to you. Good method when you need an XML file in a pinch, but it's error prone and doesn't tell you much about the content in the file.

Here is a quick example that makes use of the StringBuilder class to concatenate each different element of our XML document.


// you will need to specify the System.Xml namespace for this function
protected void Page_Load(object sender, EventArgs e)
{
     CreateStringXml();
}

private void CreateStringXml()
{
        // System.Text
        StringBuilder objString = new StringBuilder();

        objString.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        objString.Append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
        objString.Append("<url>");
        objString.Append("<loc>http://www.example.com/</loc>");
        objString.Append("<lastmod>2005-01-01</lastmod>");
        objString.Append("<changefreq>monthly</changefreq>");
        objString.Append("</url>");
        objString.Append("</urlset>");

Our objString object now holds a full XML document, albeit still in string format. Up next we'll use the StreamWriter and write the stream, obviously. After that we close our reader and we're done. We have a shiny new XML file.


        // System.IO
        StreamWriter writer = new StreamWriter(Server.MapPath("~/xml1.xml"));
        writer.Write(objString.ToString());
        writer.Close();
}

You don't need to use a StringBuilder for this, but more than likely you'll be working with a much larger dataset than what I have in the example, and a StringBuilder is the better approach for that compared to regular string concatenation. In order to use the StringBuilder you will need to specify the System.Text namespace. Also to use the StreamWriter class you will need to specify the System.IO namespace.

2. Create An XMLDocument Object

This approach does have a slight learning curve, as there are a good number of classes to work with and functions to call that are very specific. It offers more exact control of the XML document however. You create an XmlDocument when you need to process an XML tree or will be inserting elements in a non-sequential manner. But you choose your poison. It will do the job if need be. Below is the code to create a new Xml Document and then simply add an XML declaration and a namespace. As you can see it's quite a bit of code compared to our example above, but on the upside every XML element is it's own object, with functions and properties. It does offer validation, and you can manipulate the XML in any way that you would want.


private void CreateXmlDocument()
{
        XmlDocument doc = new XmlDocument();

We'll start by declaring a new object of type XmlDocument, which lives in the System.Xml namespace.


        //Create an XML declaration (xml version="1.0"?)
        XmlDeclaration xmldecl;
        xmldecl = doc.CreateXmlDeclaration("1.0",null,null);

        //Add the new node to the document
        //declaration must be the first line in the file
        XmlElement root = doc.DocumentElement;
        doc.InsertBefore(xmldecl, root);

        // adding the urlset namespace attributes to the urlset element
        XmlNode urlset = doc.CreateNode(XmlNodeType.Element, "urlset", "");
        XmlAttribute att = doc.CreateAttribute("xmlns");
        att.Value = "http://www.sitemaps.org/schemas/sitemap/0.9";
        XmlAttribute att2 = doc.CreateAttribute("xmlns:image");
        att2.Value = "http://www.google.com/schemas/sitemap-image/1.1";
        urlset.Attributes.Append(att);
        urlset.Attributes.Append(att2);

        XmlNode node = doc.CreateNode(XmlNodeType.Element, "url", "");
        XmlNode loc = doc.CreateNode(XmlNodeType.Element, "loc", "");
        XmlNode image = doc.CreateNode(XmlNodeType.Element, "image", "");
        XmlNode priority = doc.CreateNode(XmlNodeType.Element, "priority", "");
        XmlNode lastmod = doc.CreateNode(XmlNodeType.Element, "lastmod", "");
        XmlNode changefreq = doc.CreateNode(XmlNodeType.Element, "changefreq", "");

        // DateTime object used to format our date later
        DateTime dt = DateTime.Parse("1/1/2014");

        // whichever url format you may have
        loc.InnerText = "http://www.yoursite.com";
        lastmod.InnerText = dt.ToString("yyyy-MM-dd");  // date must be in this format to be valid
        priority.InnerText = "0.9";
        changefreq.InnerText = "daily";

        node.AppendChild(loc);
        node.AppendChild(lastmod);
        node.AppendChild(priority);
        node.AppendChild(changefreq);
        urlset.AppendChild(node);  // everything gets appended to our first urlset element

       doc.AppendChild(urlset);   // urlset is appended to our main document
       
       // sitemaps are normally found in the root of your website
       // but feel free to save the sitemap in whatever location makes sense to your website
       doc.Save(Server.MapPath("~/sitemap.xml"));
}

3. Use The XmlWriter Class

Yet a third approach, depending on your needs. The XmlWriter class is a forward only non cached way to write xml content to a stream. The benefit in this? It's fast. It doesn't build up an entire document in memory like the XmlDocument does. And I have encountered issues in the past with memory when working with large xml feeds and the XmlDocument. If all you need is to generate an XML file on the fly, then this would be the way to go.


private void TestXmlWriter()
{
        XmlWriterSettings settings = new XmlWriterSettings();
        string url = Server.MapPath("~/xml2.xml");

        using (XmlWriter writer = XmlWriter.Create(url, settings))
        {
            writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
            writer.WriteStartElement("url");
            writer.WriteElementString("loc", "http://www.example.com");
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Flush();
            writer.Close();
        }
}

The fastest approach so far is by using the XmlWriter class. It's fast, it offers validation using the latest xml standards, and it is simple to follow. If you look at all 3 examples, it requires the least amount of code and has the cleanest layout.

So there you have 3 ways to create XML files in ASP.NET, with #3 coming in as the quickest more error proof method and with #2 being the most versatile.

Land your next big coding job. Search through 1000's of job listings.

Discussion / Comments / Questions

No messages posted yet

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post comment