David Diaz
David Diaz

Reputation: 148

XSLT replace variable element text

I have an example document that looks like this

<document>
   <memo>
       <to>Allen</to>
       <p>Hello! My name is <bold>Josh</bold></p>
       <p>It's nice to meet you <bold>Allen</bold>. I hope that we get to meet up more often.</p>
       <from>Josh</from>
   <memo>
</document>

and this is my XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:company="http://my.company">
    <xsl:output method="html"/>

    <xsl:variable name="link" select="company:generate-link()"/>

    <xsl:template match="/document/memo">
        <h1>To: <xsl:value-of select="to"/></h1>

        <xsl:for-each select="p">
            <p><xsl:apply-templates select="node()" mode="paragraph"/></p>
        </xsl:for-each>

        <xsl:if test="from">
            <p>From: <strong><xsl:value-of select="from"/></strong></p>
        </xsl:if>

        <xsl:copy-of select="$link"/>
    </xsl:template>

    <xsl:template match="bold" mode="paragraph">
        <b><xsl:value-of select="."/></b>
    </xsl:template>

    <xsl:template match="text()" mode="paragraph">
        <xsl:value-of select="."/>
    </xsl:template>
</xsl:stylesheet>

and the variable link contains the following example node:

<a href="#doAction"></a>

When I do a copy-of out the variable link it prints out the node correctly (but obviously without any text). I want to insert it into the document and replace the text using XSLT. For example, the text could be:

View all of <xsl:value-of select="/document/memo/from"/>'s documents.

So the resulting document would look like:

<h1>To: Allen</h1>
<p>Hello! My name is <b>Josh</b></p>
<p>It's nice to meet you <b>Allen</b>. I hope that we get to meet up more often.</p>
<from>Josh</from>
<a href="#doAction">View all of Josh's documents.</a>

I have been searching the internet on how to do this but I couldn't find anything. If anyone could help I would appreciate it a lot!

Thanks, David.

Upvotes: 0

Views: 1132

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

You haven't said which XSLT processor that is nor have you shown the code of that extension function to allow us to understand what it returns but based on your comment saying it returns a node you can usually process it further with templates so if you use <xsl:apply-templates select="$link"/> and then write a template

<xsl:template match="a[@href]">
  <xsl:copy>
    <xsl:copy-of select="@*"/>
    View all of <xsl:value-of select="$main-doc/document/memo/from"/>'s documents.
  </xsl:copy>
</xsl:template>

where you declare a global variable <xsl:variable name="main-doc" select="/"/> you should be able to transform the node returned from your function.

Upvotes: 1

Related Questions