CLR UDF Example: TransformXML.cs
/*=====================================================================
File: TransformXML.cs
Summary: A CLR UDF to transform XML using an XSLT
Date: Apr 5, 2005
---------------------------------------------------------------------
Copyright (C) Microsoft Corporation. All rights reserved.
This source code is intended only as a supplement to a Microsoft
WebCast.
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
======================================================= */
using System;
using System.Data.SqlTypes;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
/// <summary>
/// Implements CLR UDF to transform an XML datatype instance with XSLT stylesheet
/// (provided with local file path).
/// </summary>
public class TransformXml
{
public static SqlXml ApplyXslTransform (
SqlXml XmlData,
string xslPath)
{
// Load XSL transformation
XslCompiledTransform xform = new XslCompiledTransform();
xform.Load (xslPath);
// Execute/Cache results
XmlDocument resultsDoc = new XmlDocument();
XPathNavigator resultsNav = resultsDoc.CreateNavigator();
// using makes sure that we flush the writer at the end
using (XmlWriter writer = resultsNav.AppendChild())
{
xform.Transform(XmlData.CreateReader(), writer);
}
// Return results
SqlXml retSqlXml = new SqlXml (resultsNav.ReadSubtree());
return (retSqlXml);
}
}