Jesper Tverskov, June 22, 2008

Create XML with W3C DOM in ASP.NET

In ASP.NET we have three main APIs for creating XML from scratch. We can use the new LINQ to XML, the XmlWriter class or W3C DOM. In this tutorial we look at W3C DOM. The idea is only to show a basic example. There are many more properties and methods and ways of achieving the same result than indicated below. You must look up the proper documentation for all the details.

1. Create products.xml

I use the following XML document, products.xml, in many of my XML tutorials. How could it be created using W3C DOM. To get an idea, we will only create the XML Declaration, the top-element and the first product element with attribute and children, and save it to a file.

<?xml version="1.0" encoding="utf-8"?>
  <product id="p3">

At the end of the ASP.NET code shown below, we use Response.Redirect to the new file to get it loaded in the browser. The code will work right away if copied out of this document and saved with the proper file names.

2. W3C DOM

2.1 create-xml-w3cdom.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="create-xml-w3cdom.aspx.cs" Inherits=" create_xml_w3cdom" %>

2.2 create-xml-w3cdom.aspx.cs

using System;
using System.Xml;

public partial class create_xml_w3cdom : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        XmlDocument doc = new XmlDocument();

        // create XML Declaration
        XmlDeclaration xmldec = doc.CreateXmlDeclaration("1.0", "UTF-8", "");

        // create DocumentElement (top-element)
        XmlElement products = doc.CreateElement("products");

        // create element and attriute
        XmlElement product = doc.CreateElement("product");
        product.SetAttribute("id", "p3");

        // create name element
        XmlElement name = doc.CreateElement("name");
        XmlText nameText = doc.CreateTextNode("Alpha");

        // create price element
        XmlElement price = doc.CreateElement("price");
        XmlText priceText = doc.CreateTextNode("1200");

        // create stock element
        XmlElement stock = doc.CreateElement("stock");
        XmlText stockText = doc.CreateTextNode("19");

         // create country element
        XmlElement country = doc.CreateElement("country");
        XmlText countryText = doc.CreateTextNode("Germany");
        Response.Redirect("products-w3cdom.xml"); // load file in browser

        /* In our simple example we only have one product element. In the full example we have many. For that reason we use the XPath expression "product[1]". */

The W3C DOM has a bad reputation. It takes too much code and we can not indent the code in a meaningful way to make it look like the hierarchy we are creating. Microsoft has added some extensions to W3C DOM like "InnerText" and "InnerXML" (not used above) to make our life easier and to confuse us if we also use W3C DOM in other contexts.

Updated 2008-07-04