开发者

Is it possible to use the sprintf() function in XSLT?

I'd like to do something like "Hello %s" and have "World" in another variable.

Of course I could do this simple case using string replacement but if possible I'd like all sprin开发者_运维问答tf() features like argument reordering, which would be very complex to do myself.


The XML/XSLT equivalent of Hello World is this:

We have this XML document:

<t>Hello <rep/>!</t>

and use this transformation on it:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="rep">
  <xsl:value-of select="'World'"/>
 </xsl:template>
</xsl:stylesheet>

The wanted result is produced:

<t>Hello World!</t>

Do note:

  1. We use and override the identity rule. This is the most fundamental XSLT design pattern.

  2. We can intersperse a constant content with many different replacement elements and thus have a "fill-in the blanks" technique.

  3. Using this technique a full separation between content and processing logic can be achieved. The XSLT code doesn't know what source XML document it is processing (the document URL can even be passed as parameter). The same XSLT stylesheet can be used any fill-in the blanks document and any fill-in the blanks document can be processed by different XSLT stylesheets. This separation achieves maximum flexibility and maintainability.

  4. If you only want just text to be produced, this can also be done easily -- for example using <xsl:output method="text"/>


If you are performing the transform inside a language that supports extending XSLT using an extension object (such as one of the .NET languages or PHP); then you can simply create a function to do this and call it from within your XSLT.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜