XSLT Helper class


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. using System;
  2. using System.IO;
  3. using System.Xml;
  4. using System.Xml.Xsl;
  5.  
  6. namespace [[Name Space]]
  7. {
  8. public class [[Class Name]]
  9. {
  10. /// <summary>
  11. /// Transforms the supplied xml using the supplied xslt and returns the
  12. /// result of the transformation
  13. /// </summary>
  14. /// <param name="xml">The xml to be transformed</param>
  15. /// <param name="xslt">The xslt to transform the xml</param>
  16. /// <returns>The transformed xml</returns>
  17. public string TransformXml(string xml, string xslt)
  18. {
  19. // Simple data checks
  20. if (string.IsNullOrEmpty(xml))
  21. {
  22. throw new ArgumentException("Param cannot be null or empty", "xml");
  23. }
  24. if (string.IsNullOrEmpty(xslt))
  25. {
  26. throw new ArgumentException("Param cannot be null or empty", "xslt");
  27. }
  28.  
  29. // Create required readers for working with xml and xslt
  30. StringReader xsltInput = new StringReader(xslt);
  31. StringReader xmlInput = new StringReader(xml);
  32. XmlTextReader xsltReader = new XmlTextReader(xsltInput);
  33. XmlTextReader xmlReader = new XmlTextReader(xmlInput);
  34.  
  35. // Create required writer for output
  36. StringWriter stringWriter = new StringWriter();
  37. XmlTextWriter transformedXml = new XmlTextWriter(stringWriter);
  38.  
  39. // Create a XslCompiledTransform to perform transformation
  40. XslCompiledTransform xsltTransform = new XslCompiledTransform();
  41.  
  42. try
  43. {
  44. xsltTransform.Load(xsltReader, new XsltSettings(true, true), null);
  45. xsltTransform.Transform(xmlReader, transformedXml);
  46. }
  47. catch (XmlException xmlEx)
  48. {
  49. // TODO : log - "Could not load XSL transform: \n\n" + xmlEx.Message
  50. throw;
  51. }
  52. catch (XsltException xsltEx)
  53. {
  54. // TODO : log - "Could not process the XSL: \n\n" + xsltEx.Message + "\nOn line " + xsltEx.LineNumber + " @ " + xsltEx.LinePosition)
  55. throw;
  56. }
  57. catch (Exception ex)
  58. {
  59. // TODO : log
  60. throw;
  61. }
  62.  
  63. return stringWriter.ToString();
  64. }
  65. }
  66. }
  67.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.