Passing xml between xsl and a helper method
In that, I'm also quite frequently using helper classes in assemblies called directly from the xsl, on which I have posted before.
Mostly I'm passing simple values between the two such as strings and ints, but every now and then I need to pass a whole xml struture between them - it might be a node-set from the xsl that needs to be processed by the helper method, it might be that the method returns an xml fragment the xsl needs to then iterate on or, most likely, it will be both.
The way to do it is quite simply to use the XPathNodeIterator class in the System.Xml.XPath namespace.
I did not know about this class until I had to do this bit, so it has to be worth posting (for myself if not for anyone else).
To demonstrate it's use I've create a helper method as follwos -
public XPathNodeIterator processXml(XPathNodeIterator nodeset)
XPathNavigator nav = nodeset.Current;
XPathNodeIterator i = nav.Select("//*");
As you can see this method doesn't really do much, but it already demonstrates how to receive an xml node-set and how to return one.
the helper method can work with the following xsl -
<xsl:variable name="MyNodeSet" select="<some xpath>"/>
<xsl:variable name="HelperResult" select="helpers:processXml($MyNodeSet)"/>
<xsl:value-of select="$HelperResult/<some other xpath>"/>
The next challange was how to create a brand new XPathNodeIterator, here's one way (assuming xmlDoc is an XmlDocument that contains the xml you need to return -
xPathNav = xmlDoc.CreateNavigator();
XPathExpression xPathExpr = xPathNav.Compile("
XPathNodeIterator xPathNodI = xPathNav.Select(xPathExpr);