Transforming Xml with Xsl in Memory

I have wanted to be able to transform Xml data that is in memory with Xsl.

This method will allow the transformation of the Xml using the Xsl and return what has been transformed as a string.

  /// <summary>
  /// In memory XSL transformation.
  /// </summary>
  /// <param name="xmlText">The XML text.</param>
  /// <param name="xslText">The XSL text.</param>
  /// <returns>Xsl transformation of data of the Xml.</returns>
  private string InMemoryXslTransformation(string xmlText, string xslText) {

    // load instance of xml to a XmlDocument from xmlText
    XmlDocument xml = new XmlDocument();
    xml.InnerXml = xmlText;

    // load instance of xsl to a XmlDocument from xslText
    XmlDocument xsl = new XmlDocument();
    xsl.InnerXml = xslText;

    // xsl argument list for xsl compiled transformation
    XsltArgumentList al = new XsltArgumentList();

    // hold output from xsl compiled transformation
    StringWriter sw = new StringWriter();

    // create instance of XslCompiledTransform object
    XslCompiledTransform xslTrans = new XslCompiledTransform();

    // load the XSLT style sheet
    xslTrans.Load(xsl);

    // transfor the XML file using the XSLT file
    // store the output in a StringWriter object
    xslTrans.Transform(xml, al, sw);

    // output message
    return sw.ToString();
  }

Comments are closed.