Transform an XML String using an XSLT File into another String
By Ken Fitzpatrick
The following code snippet is a shared function (or static method) that takes an XML String (string type) and a pathname for an XSLT file and returns a string of XML that has been transformed based on the rules in the XSLT file.
'This function will transform an xml string into another string based on the
passed in xslt filename.
Public Shared Function transformXML(ByVal xmlString As String, ByVal xsltPathName
As String) As String
Dim xmlDoc As XmlDocument = New XmlDocument()
Dim xmlNewDoc As XmlDocument = New XmlDocument()
Dim xmlTransform As New Xsl.XslCompiledTransform
xmlDoc.LoadXml(xmlString)
xmlTransform.Load(xsltPathName)
' stream the xml:
Dim data() As Byte = Encoding.UTF8.GetBytes(xmlDoc.InnerXml)
Dim ms As IO.MemoryStream = New IO.MemoryStream(data)
Dim input As XmlReader = XmlReader.Create(ms)
' create output streams:
Dim buffer As New IO.MemoryStream
Dim sw As IO.StreamWriter = New IO.StreamWriter(buffer)
' transform the document:
xmlTransform.Transform(input, Nothing, sw)
' turn results into a string:
Dim chars() As Byte = buffer.ToArray
Dim output As String = Encoding.UTF8.GetString(chars)
Return output
End Function
Transform an XML String using an XSLT File into another String (265 Views)