Jesper Tverskov, July 4, 2008

Create XML with Parse(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 Parse(string), one of many ways to create XML from scratch in LINQ to XML.

1. Create products.xml

I use the following XML document, products.xml, in many of my XML tutorials. How could it be created using Parse(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 just 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. Parse(string)

2.1 create-xml-parse.aspx

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

2.2 create-xml-parse.aspx.cs

using System;
using System.Xml.Linq;

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

      products.Save(Server.MapPath("products-parse.xml"));
      Response.Redirect("products-parse.xml"); //load file in browser
    }
}

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

For more information about LINQ to XML: .NET Language-Integrated Query for XML Data.

Updated 2008-07-07