XSLT - Tokenizing template to italicize and bold XML element text

寵の児 提交于 2019-12-01 13:12:36

"I'm wondering if it is possible to add to this tokenizing system the ability to bold or italicize certain words in my XML element text using the same delimiter approach with a delimiter on each side of a word to indicate either bold or italicized."

Yes, it is possible. And at this point you should be able to implement this yourself, using the same principle as the one utilized by the tokenizing template (which you call "split"). Creating a token tagged as <li> is no different from creating one tagged <b> or <i>.


Edit:

In response to:

"I think there is a difference: while partitioning the text into li elements, every fragment of text eventually ends up inside a list item, and the delimiter ; marks where a list item should end and another immediately start. Conversely, the bold or italic markup would apply only to a text portion between a starting and an ending delimiter."

The required change is rather trivial. Consider the following example:

<xsl:template name="italic">
    <xsl:param name="text"/>
    <xsl:param name="delimiter" select="'*'"/>
    <xsl:choose>
        <xsl:when test="contains($text, $delimiter) and contains(substring-after($text, $delimiter), $delimiter)">
            <xsl:value-of select="substring-before($text, $delimiter)"/>
            <i>
                <xsl:value-of select="substring-before(substring-after($text, $delimiter), $delimiter)"/>
            </i>
            <!-- recursive call -->
            <xsl:call-template name="italic">
                <xsl:with-param name="text" select="substring-after(substring-after($text, $delimiter), $delimiter)"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

When this template is called as:

<p>
    <xsl:call-template name="italic">
        <xsl:with-param name="text" select="input"/>
    </xsl:call-template>
</p>

with the input being:

<input>Lorem ipsum *dolor* sit amet, *consectetuer* adipiscing * elit.</input>

the result will be:

<p>Lorem ipsum <i>dolor</i> sit amet, <i>consectetuer</i> adipiscing * elit.</p>

Note that the last, odd delimiter is passed to the output as is.

You could generalize this template to handle other types of markup (e.g. bold) by parametrizing the name of the token element to create.

--
P.S. This solution proudly uses xsl:choose. xsl:choose is an integral part of the XSLT language, and there is absolutely nothing wrong with using it to its full advantage. It adds clarity to the code, while artificial attempts to avoid using it only end up obfuscating the code unnecessarily.

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