Jesper Tverskov, July 7, 2008

Read XML with XmlReader

In ASP.NET we have four main APIs for reading XML. We can use the new LINQ to XML, the XmlReader, the XPathDocument and the XmlDocument classes. In this tutorial we look at XmlReader. The idea is only to show a basic example for comparison.

1. Read products.xml

I use the following XML document, products.xml, in many of my XML tutorials. How could it be transformed into an XHTML table using XmlReader? To make the example more interesting, we use CSS for colors, etc.

The idea is only to show a basic example of how to use XmlReader. 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.

2. XmlReader

2.1 read-xml-reader.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="read-xml-reader.aspx.cs" Inherits="read_xml_reader" %><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Read XML with XmlReader</title>
    <style type="text/css">table, td, th{border:1px solid silver; border-collapse:collapse}th{background-color:mistyrose}tr.alt1{background-color: ivory}tr.alt0{background-color: azure}</style>
  </head>
  <body>
    <h1>Using XmlReader</h1>
    <div id="div1" runat="server" />
  </body>
</html>

2.2 read-xml-reader.aspx.cs

using System;
using System.IO;
using System.Xml;

public partial class read_xml_reader : System.Web.UI.Page
{
  string tr; // table rows
  string id; // product id
  string name; // product name
  string price; // product price
  string stock; // product stock
  string country; // product country
  int counter = 0;

  protected void Page_Load(object sender, EventArgs e)
  {
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.IgnoreWhitespace = true;
    settings.IgnoreComments = true;

    string productsFile = Path.Combine(Request.PhysicalApplicationPath, "products.xml");

    using (XmlReader reader = XmlReader.Create(productsFile, settings))
    {
      while (reader.Read())
      {
        if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "product")
        {
          counter += 1;
          reader.MoveToAttribute("id");
          id = reader.Value;reader.MoveToElement();
          reader.ReadToDescendant("name");
          name = reader.ReadElementContentAsString();
          reader.MoveToContent();
          price = reader.ReadElementContentAsString();
          reader.MoveToContent();
          stock = reader.ReadElementContentAsString();
          reader.MoveToContent();country = reader.ReadElementContentAsString();

          tr += "<tr class='alt" + (counter % 2) + "'><td>" + id + "</td><td>" + name + "</td><td>" + price + "</td><td>" + stock + "</td><td>" + country + "</td></tr>";
        }
      }
    }
  string hd = "<th>id</th><th>name</th><th>price</th><th>stock</th><th>country</th>"; div1.InnerHtml = "<table cellspacing='0' cellpadding='5'>" + hd + tr + "</table>";
  }
}

In our small example we don't need to use "settings" but since it is almost always used for fine tuning, we do it too in order to indicate how it works.

Updated 2008-07-08