XML transformations in .NET - Part I

Presenting the data

Rendering this raw data on a webpages requires an XSLT template that converts or transforms the xml into HTML. Below is a sample xsl that will process the “computers.xml” file.

computers.xsl

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="computers">
<h2>Computer Shopper</h2>

<b>Computyer Type:</b> <xsl:value-of select="computer/@type"/><br/>
<b>PC Specs:</b> <br/>
<b>CPU:</b> <xsl:value-of select="computer/processor"/><br/>
<b>Ram:</b> <xsl:value-of select="computer/ram"/><br/>
<p />

<b>Price: </b> <xsl:value-ofselect="computer/price/@currencySymbol"/>
<xsl:value-of select="computer/price"/>
</xsl:template>
</xsl:stylesheet>

Here are the results of the transformation:

.NET Transformation Objects:

So how do you tell an XSL to process an xml file for transformation? There are a few ways. This article focuses on the built in .NET Transformer class. First familiarize yourself with the Code-behind below:

Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.XPath
Imports System.Xml.Xsl
Public Class WebForm1
    Inherits System.Web.UI.Page
    Protected WithEvents ltl_htmlResults As System.Web.UI.WebControls.Literal

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim XMLDoc As XPathDocument
        Dim XSLTDoc As XslTransform
        'Prepare StringWriter for results
        Dim sw As StringWriter = New StringWriter()
        'Load xml file into XMLDoc
        XMLDoc = New XPathDocument(Server.MapPath("computers.xml"))
        'Load XSL
        XSLTDoc = New XslTransform()
        XSLTDoc.Load(Server.MapPath("computers.xsl"))
        'Transform XMLDoc and dump HTML results to stringwriter -> sw
        XSLTDoc.Transform(XMLDoc, Nothing, sw)
        'Pull results out of stringwriter and populate literal
        ltl_htmlResults.Text = sw.ToString()
    End Sub

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The trouble with programmers is that you can never tell what a programmer is doing until it's too late.” - Seymour Cray