I have sufficiently commented the code for understanding and clarity but I will elaborate further on what’s going on.
First, notice that I have imported the necessary Namespaces.
Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.XPath
Imports System.Xml.Xsl
Second, all my processing is occurring within the scope of Page Load. In a real word business class application, code like this will most likely be encapsulated into reusable assemblies.
If you’ll notice, a StringWriter
object was declared:
'Prepare StringWriter for results
Dim sw As StringWriter = New StringWriter()
The stringwriter variable “sw
” will be used later
to dump the HTML transformation results into. To perform a transformation, two
documents are needed, the XSL and XML files. First, load up the XML document:
'Load xml file into XMLDoc
XMLDoc = New XPathDocument(Server.MapPath("computers.xml"))
I am loading my XML document into an XPathDocument
object. The
XPathDocument
object is optimized for efficient XSLT performance.
Next I call the load()
method of the XSLTransform class to load
the xsl file:
'Load XSL
XSLTDoc = New XslTransform()
XSLTDoc.Load(Server.MapPath("computers.xsl"))
Now that we have both XML and XSL loaded into memory, calling the Transform()
method of the XSLTransform
object will do all the xslt processing
for us.
'Transform XMLDoc and dump HTML results to stringwriter -> sw
XSLTDoc.Transform(XMLDoc, Nothing, sw)
The Transform() method is overloaded. In this case it accepts three parameters:
- The XML document
- An Argument list
- The
StringWriter
We are not using any arguments for this transformation so passing in “Nothing
”
is acceptable. Also, notice that we finally passed in the StringWriter
object that was declared earlier. As I have stated, calling Transform()
will populate the StringWriter
with the HTML results. We can then
use the results of the StringWriter
for page output:
'Pull results out of stringwriter and populate literal
ltl_htmlResults.Text = sw.ToString()
So there you have it, basic XSLT Transformations in .NET. In Part 2 of XSLT Transformations, I’ll dig a little deeper into the XSLTransform class. We’ll examine the usage of XSL Arguments and Extension Objects, allowing our XSL templates to perform more dynamic operations on XML data.
Comments