Pass QueryString Variable to XSLT

So I was building an annual meeting program that needed to grab certain nodes from a remote XML file based on a session ID. I figured I could just pass the session id as a querystring variable and the XSLT file could manipulate it, but it turned out to be slightly more complicated than that. Being the novice that I am, I thought I ought to document it. It really consists of three parts: 1) grabbing the querystring, 2) pass the variable to the XSLT as an argument, and 3) using the passed paramenter in the XSLT to output the correct HTML. Here is the page load for the aspx page, in VB. Note that I also added code to cache the remote XML file on the server, as this greatly increases the loading speed:

  Sub Page_Load(sender As Object, e As EventArgs)

    'Grabbing the querystring = the sess_id to look up the session
    Dim sess_id As String
	sess_id = Request.QueryString("sess_id")


    'Grabbing the remote XML file
    Dim strXmlSrc  As String = "http://www.yourremoteXMLfile.com"

    ' Path to our XSL file. 
    Dim strXslFile As String = Server.MapPath("stylethisthing.xsl")

    'This adds the querystring variable to be passed to the XSL
    Dim args As XsltArgumentList = New XsltArgumentList
    args.AddParam("sess_id", "", sess_id)

  'Check to see if the cached XML file exists. If not, cache it and expire it after 1 hour (absolute, regardless of user)
  If Cache.Item("RWProgram") Is Nothing Then
    ' Load our XML file into the XmlDocument object.
    Dim myXmlDoc As XmlDocument = New XmlDocument()
    myXmlDoc.Load(strXmlSrc)
    Cache.Insert("RWProgram", myXmlDoc, Nothing, DateTime.Now.AddMinutes(60), TimeSpan.Zero)
  End If

    ' Load our XSL file into the XslTransform object.
    Dim myXslDoc As XslTransform = New XslTransform()
    myXslDoc.Load(strXslFile)

    'Use a stringbuilder to write the HTML
    Dim myStringBuilder As StringBuilder = New StringBuilder()
    Dim myStringWriter  As StringWriter  = New StringWriter(myStringBuilder)

    ' Transform this junks
    myXslDoc.Transform(Cache.Item("RWProgram"), args, myStringWriter)

    ' Spit out the HTML
    programdetails.Text = myStringBuilder.ToString


  End Sub

Then, add this code to the top of your XSLT:

<xsl:param name="sess_id" />

You can now reference the “sess_id” parameter anywhere in your XSLT with “$sess_id”. I used this in my XPATH to grab the correct node for the meeting session, so that we had a fully dynamic meeting program. Not the most advanced thing, but it works 😉

Published by

Hal

Aside from being a champion yo-yoer, I am the full-time computer geek at the American Society of Nephrology. I recently completed my MBA from George Washington University which I am hoping will enable me to finally afford my own bad habits. I also do freelance design, specializing in Flash, PHP, and ASP/ASP.NET.

Leave a Reply

Your email address will not be published. Required fields are marked *