looking at the XSLCompiledTransform Class in .NET at trying to find a concise way to use it in F#. I am unfamiliar with string readers/writers but am looking at that as primary method to accomplish this. Or do I want XML readers?
I have a function that will take two arguments - an XML string and an XSLT stylesheet. I want to return a string of XML.
let applyXSLTransform xml xslFile =
let xslt = XslCompiledTransform()
xslt.Load(xslFile)
xslt.Transform(xml, outputToString); //This bit
It's nice and easy to do with files but seems a bit more involved to read and write to strings. I have seen a few C# samples and not having immediate success in getting them to work so still doing research onto readers and writers!
Cheers
I don't think there is an easier way to use the API than using the XmlReader
and XmlWriter
interfaces. This is unfortunately quite tedious, but the following should do the trick:
open System.IO
open System.Text
open System.Xml
open System.Xml.Xsl
let applyXSLTransform xml (xslFile:string) =
let xslt = XslCompiledTransform()
let sbuilder = StringBuilder()
use swriter = new StringWriter(sbuilder)
use sreader = new StringReader(xml)
use xreader = new XmlTextReader(sreader)
use xwriter = new XmlTextWriter(swriter)
xslt.Load(xslFile)
xslt.Transform(xreader, xwriter)
sbuilder.ToString()
The code constructs StringBuilder
, which is an in-memory object for constructing strings. It wraps this around StringWriter
and XmlTextWriter
to be passed to the Transform
method. At the end, you read the contents of the StringBuilder
using the ToString
method. Similar thing happens to create XmlTextReader
for data from StringReader
, which contains your input XML.