How to declare a user-defined function returning node-set?

痞子三分冷 提交于 2019-12-06 05:31:43

问题


I want something like this:

<msxsl:script language="C#">
   ??? getNodes() { ... return ... }
</msxsl:script>

<xsl:for-each select="user:getNodes()">
    ...
</xsl:for-each>

What return type should i use for getNodes() and what should i put in it's body?


回答1:


In principle you need to use the XPathNodeIterator to return node sets (as Samjudson says). I take it that the example you gave is a degenerated function, as you do not supply it with any parameters. However, I think it is instructive the see how you could fabricate nodes out of thin air.

<msxsl:script language="C#">
   XPathNodeIterator getNodes() 
   { 
      XmlDocument doc = new XmlDocument();
      doc.PreserveWhitespace = true;
      doc.LoadXml("<root><fld>val</fld><fld>val2</fld></root>");
      return doc.CreateNavigator().Select("/root/fld");
   }
</msxsl:script>

However, typically you would want to do something in your function that is not possible in xslt, like filtering a node set based on some criteria. A criteria that is better implemented through code or depends om some external data structure. Another option is just that you would to simplify a wordy expression (as in the example bellow). Then you would pass some parameters to you getNodes function. For simplicity I use a XPath based filtering but it could be anything:

   <msxsl:script language="C#">
       XPathNodeIterator getNodes(XPathNodeIterator NodesToFilter, string Criteria)
      {
         XPathNodeIterator x = NodesToFilter.Current.Select("SOMEVERYCOMPLEXPATH["+Criteria+"]");
         return x;
      }
   </msxsl:script>
   <xsl:for-each select="user:getNodes(values/val,'SomeCriteria')">
    ...
  </xsl:for-each>

Hopes this helps, Boaz




回答2:


A quick google for C# xslt msxml revealed a link to the following page which gives many examples of extending XSLT in microsoft environments.

http://msdn.microsoft.com/en-us/magazine/cc302079.aspx

Specifically the section on Mapping Types between XSLT and .Net gives you exactly the information you need:

W3C XPath Type - Equivalent .NET Class (Type)

  • String - System.String
  • Boolean - System.Boolean
  • Number - System.Double
  • Result Tree Fragment - System.Xml.XPath.XPathNavigator
  • Node Set - System.Xml.XPath.XPathNodeIterator

So in your example I would try XPathNodeLiterator.



来源:https://stackoverflow.com/questions/152822/how-to-declare-a-user-defined-function-returning-node-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!