Hey I need to trim content within in each <a> tag to a character limit 20 within a description node using XML 1.0. Here is the XML
<description>
This is text <a href="http://stackoverflow.com/posts/14718323/edit">http://stackoverflow.com/posts/14718323/edit</a>.
Also here is more text than we have another
<a href="http://stackoverflow.com/posts/14718323/edit">http://stackoverflow.com/posts/14718323/edit</a>.
</description>
What I need it to turn into is this:
<description>
This is text <a href="http://stackoverflow.com/posts/14718323/edit">http://stacko</a>.
Also here is more text than we have another
<a href="http://stackoverflow.com/posts/14718323/edit">http://stacko</a>.
</description>
I can do most the logic, but I’m having trouble doing a “for-each” that searches through the description node and transforms “each” < a >.
Does this make sense? Any help appreciated.
** EDIT 2/7/13 *
Based on the answers provided here is where I am at now.
<xsl:template match="/">
<xsl:apply-templates select="//description"/>
</xsl:template>
<xsl:template match="a">
<a href="{@href}">
<xsl:value-of select="substring(normalize-space(),1,20)"/>
</a>
</xsl:template>
The problem is “apply-templates” won’t work because I have multiple templates in my XSL. I need to call a template specifically, so I assumed “call-template” would be the route to go. The only problem with “call-template” is I don’t know how to specify an specific XML node to reference. Here is how I’ve hacked it so far (deosn’t work):
<xsl:template match="/">
<xsl:call-template name="trim_text"/>
</xsl:template>
<xsl:template name="trim_text" match="//description">
<a href="{@href}">
<xsl:value-of select="substring(normalize-space(),1,20)"/>
</a>
</xsl:template>
The initial ‘call-template’ needs to be in a <xsl:template match="/"> because this is going in a much larger function. So I need 3 things:
1) the HREF to stay consistent with what is in the XML
2) The text between the <a> tag to be trimmed to 20px
3) I need to call this template from inside a much larger xsl template which does a lot of transformation on the XML. This will be of around 7 template calls.
Template modes may be what you are looking for
When you specify a mode with
apply-templates, only templates that are marked with the same mode are considered when finding the template to apply to each node (plus the default implicit template that matches all element nodes and recursively applies templates to children using the same mode, but that doesn’t apply here as we have an identity template). This example template foraelements doesn’t allow for links that contain other tags, for examplewould become
If you want to preserve such markup it gets much more complicated. You can’t do it with the obvious approach of
because this would treat each text node in isolation, and produce
(as “This is a ” and “very” are already shorter than 20 characters, and ” long piece of text ” is the truncation to 20 characters of ” long piece of text used as…”)