Jesper Tverskov, June 25, 2008

Create XML with LINQ to XML 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 LINQ to XML. 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 LINQ to XML. 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 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. LINQ to XML

2.1 create-xml-linq.aspx

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

2.2 create-xml-linq.aspx.cs

using System;
using System.Xml.Linq;

public partial class create_xml_linq : System.Web.UI.Page
  protected void Page_Load(object sender, EventArgs e)
      XDocument products = new XDocument(
        new XDeclaration("1.0", "utf-8", ""),
          new XElement("products",
            new XElement("product",
              new XAttribute("id", "p1"),
              new XElement("name", "Alpha"),
              new XElement("price", "1200"),
              new XElement("stock", "19"),
              new XElement("country", "Germany")

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

The new LINQ API is lean compared to W3C DOM and XmlWriter. In our case the explicit XDeclaration is not necessary, it defaults to the same. Since we don’t declare a DOCTYPE declaration, or PIs or Comments before the top-element we don’t even need the XDocument but could have used XElement products = new XElement().

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

Updated 2008-07-04