Transform XML with XSL, and string

Posted by Marcus Hammarberg on June 14, 2007
This took us a while to find and put together. I don't want to have to go through it again.

This function takes a xml-string and transforms it with the sent-in xsl (also string). The output is returned as a memory stream that, for example, can be set in a webbrowser controls DocumentStream property.

Here is the code (yes, in my favorite new language VB.NET ;)):

Friend Shared Function TransformXML(ByVal xmlString As String, ByVal xslString As String) As MemoryStream
Dim memStream As MemoryStream = Nothing
' Create a xml document from the sent-in string
Dim xmlDoc As New XmlDocument

' Load the xsl as a xmldocument, from the sent-in string
Dim xslDoc As New XmlDocument

' Create and load an transformation
Dim trans As New XslCompiledTransform

' Create a memorystrem to hold the response
memStream = New MemoryStream()
Dim srWriter As New StreamWriter(memStream)

' Transform according to the xsl and save the result in the memStream
' variable
trans.Transform(xmlDoc, Nothing, memStream)

' Set the intial position of the memorystream
memStream.Position = 0
Catch ex As Exception
End Try
Return memStream
End Function

Published by Marcus Hammarberg on Last updated