|
Tell me who are you and what are you processing
July 28, 2004 11:36 AM
ยท Filed under #XML Tips and Tricks
This is small trick for newbies looking for a way to get URI of a source XML and the stylesheet from within XSLT stylesheet. Unfortunately neither XPath 1.0 nor XSLT1.0 don't provide any solutions for the problem. Usual answer is "pass it as a parameter". That's a good one, but not always suitable (e.g. when transforming client side with <?xml-stylesheet?> PI). Next answer is "use Saxon's saxon:system-id() extension function or write your own". Latter is what I'm going to illustrate. Simple, ain't it: <xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:ext="http://mycompany.com/mynamespace">
<msxsl:script language="javascript"
implements-prefix="ext">
function uri(nodelist) {
return nodelist[0].url;
}
</msxsl:script>
<xsl:template match="/">
<p>Currently processing XML document URI is
<tt><xsl:value-of select="ext:uri(/)"/></tt></p>
<p>Currently processing XSLT stylesheet URI is
<tt><xsl:value-of select="ext:uri(document(''))"/></tt></p>
</xsl:template>
</xsl:stylesheet>
The result (try http://www.tkachenko.com/samples/detect-uri.xml) is:
Currently processing XML document URI is http://www.tkachenko.com/samples/detect-uri.xml Currently processing XSLT stylesheet URI is http://www.tkachenko.com/samples/detect-uri.xsl PS. Of course extension functions are not portable and above works only in IE/MSXML3+. PPS. Of course it only works well when XML documents are loaded from a URI, not generated on the fly. PPPS. XPath 2.0 will fix the problem providing fn:document-uri and fn:base-uri() functions. Comments
John, as you probably know Firefox 3.0 might have some support for extension functions, but currently - I think that's IE-only feature. And about #1 - basically that is fragment identifier, so probably MSXML doesn't consider it a part of document url. Again, I don't think there is any control over it. Posted by: Oleg Tkachenko at April 8, 2007 11:17 AMIn your example http://www.tkachenko.com/samples/detect-uri.xml?1 returns the ?1 but http://www.tkachenko.com/samples/detect-uri.xml#1 does not return the #1 Any way to modify the script to get the #1
Do you know any tricks for getting the uri inside XSLT in other browsers than IE? The parameters from a uri can be very useful during the XSLT transformation when processing static xml on the server. Thank you for your very useful tip. John Perkins Post a comment
|
Subscribe to me
|