Search code examples
.netxslt.net-4.0msxml

XSLT Transformation under .net - Passed in node from XPath has no value


All,

I am using .net 4.0, and the old deprecated XslTransform() class to perform a transformation of an xml order to an html output. I have an javascript function that is passed in a node w/ the following xpath expression:

<xsl:value-of select="user:renderNode(//items/item/Comments[string-length(text()) > 0])" disable-output-escaping="yes"/>

I have verified using an xpath tool that the XPath expression returns me a node which contains text content. Unfortunately, in the javascript function itself, when I say

return node.CurrentPosition;

or

return node.Current.InnerXml;

the position is 0, and InnerXml returns the entire order instead of my text selection.

Here's the C# code:

var t = new XslTransform();
        t.Load("res/order.xsl");
        t.Transform("res/order.xml", "res/output.htm");


        string output;
        using (var reader = File.OpenText("res/output.htm"))
        {
            output = reader.ReadToEnd();
        }

And XSLT:

    <msxsl:script language="JScript" implements-prefix="user">
    <![CDATA[
        function renderNode(node) {
            return node.Current.InnerXml;

        }


    ]]>
</msxsl:script>

    <tr>
                    <td colspan="6">
                        <xsl:value-of select="user:renderNode(//items/item/Comments[string-length(text()) > 0])" disable-output-escaping="yes"/>
                    </td>
                </tr>

Solution

  • Here is a sample runnable with XslTransform and .NET, the XSLT is

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:mf="http://example.com/mf" exclude-result-prefixes="msxsl mf"
    >
      <xsl:output method="xml" indent="yes"/>
    
      <msxsl:script implements-prefix="mf" language="JScript">
      function foo(nodeIterator) {
        if (nodeIterator.MoveNext()) {
          return nodeIterator.Current.Value;
        }
        else return '';
      }
      </msxsl:script>
    
      <xsl:template match="/">
        <xsl:value-of select="mf:foo(root/item)"/>
      </xsl:template>
    </xsl:stylesheet>
    

    as you can see on the XSLT side a node-set is selected by root/item and inside the JScript function an XPathNodeIterator is received and processed.

    With an input XML of

    <root>
      <item>foo</item>
    </root> 
    

    that sample outputs a result document fragment with the string value foo.