Jesper Tverskov, June 22, 2008

Create XML with LoadXml(string) 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 the most simple method, a string loaded with LoadXml(), a Microsoft extension to W3C DOM.

1. Create products.xml

I use the following XML document, products.xml, in many of my XML tutorials. How could it be created using LoadXml(string). 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"?>
<products>
  <product id="p3">
    <nameAlfa</name>
    <price>1200</price>
    <stock>19</stock>
    <country>Germany</country>
  </product>
</products>

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. LoadXml(string)

2.1 create-xml-string.aspx

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

2.2 create-xml-string.aspx.cs

using System;
using System.Xml;

public partial class create_xml_string : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
    {
      string xmlString = "<?xml version='1.0' encoding='UTF-8'?>";
      xmlString += "<products>";
        xmlString += "<product id='p3'>";
          xmlString += "<name>Alpha</name>";
          xmlString += "<price>1200</price>";
          xmlString += "<stock>19</stock>";
          xmlString += "<country>Germany</country>";
        xmlString += "</product>";
      xmlString += "</products>";

      XmlDocument doc = new XmlDocument();
      doc.LoadXml(xmlString);
      doc.Save(Server.MapPath("products-string.xml"));

      Response.Redirect("products-string.xml"); // load file in browser
    }
}

We can also build the string as in create-xml-parse.

Updated 2008-07-07