XSLT newbie question: Please fill in the blank in the C# code fragment below:
public static string TransformXMLToHTML(string inputXml, string xsltString) { // insert code here to apply the transform specified by xsltString to inputXml // and return the resultant HTML string. // You may assume that the xslt output type is HTML. }
Thanks!
The standard way to transform XML data into other formats is by Extensible Stylesheet Language Transformations (XSLT). You can use the built-in XSLTRANSFORM function to convert XML documents into HTML, plain text, or different XML schemas. XSLT uses stylesheets to convert XML into other data formats.
Before learning XSLT, we should first understand XSL which stands for EXtensible Stylesheet Language. It is similar to XML as CSS is to HTML.
With XSLT you can transform an XML document into HTML.
How about:
public static string TransformXMLToHTML(string inputXml, string xsltString) { XslCompiledTransform transform = new XslCompiledTransform(); using(XmlReader reader = XmlReader.Create(new StringReader(xsltString))) { transform.Load(reader); } StringWriter results = new StringWriter(); using(XmlReader reader = XmlReader.Create(new StringReader(inputXml))) { transform.Transform(reader, null, results); } return results.ToString(); }
Note that ideally you would cache and re-use the XslCompiledTransform
- or perhaps use XslTransform
instead (it is marked as deprecated, though).
Just for fun, a slightly less elegant version that implements the caching suggested by Marc:
public static string TransformXMLToHTML(string inputXml, string xsltString) { XslCompiledTransform transform = GetAndCacheTransform(xsltString); StringWriter results = new StringWriter(); using (XmlReader reader = XmlReader.Create(new StringReader(inputXml))) { transform.Transform(reader, null, results); } return results.ToString(); } private static Dictionary<String, XslCompiledTransform> cachedTransforms = new Dictionary<string, XslCompiledTransform>(); private static XslCompiledTransform GetAndCacheTransform(String xslt) { XslCompiledTransform transform; if (!cachedTransforms.TryGetValue(xslt, out transform)) { transform = new XslCompiledTransform(); using (XmlReader reader = XmlReader.Create(new StringReader(xslt))) { transform.Load(reader); } cachedTransforms.Add(xslt, transform); } return transform; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With