C. Mar
C. Mar

Reputation: 149

XSLT: How to select only the text that appears before a particular nested tag without selecting the text that appears after the tag?

I am new in xslt. My xml code is:

        <tag1>
          text1
          <nestedTag Id="text2" /> 
          text3
        </tag1>

And I want to receive this output:

text1 text2 text3

I write two templates:

  <xsl:template match="tag1">
     <b>
      <xsl:apply-templates select = "nestedTag" />
      <xsl:value-of select="."/>
     </b>
  </xsl:template>


  <xsl:template match="nestedTag">
    <xsl:value-of select="@Id"/>
  </xsl:template>

But I get this:

text2 text1 text3

My question is: how to separate between text1 and text3?

Upvotes: 0

Views: 507

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167561

Your tag1 element has three child nodes, a text node, an element node and a text node. The first text node in general can be selected with text()[1], the first child node in general with node()[1].

But in the context of your sample and with XSLT it suffices to replace

  <xsl:apply-templates select = "nestedTag" />
  <xsl:value-of select="."/>

with

  <xsl:apply-templates/>

as that will process all child nodes and the built-in templates for text nodes will output them.

Upvotes: 1

Related Questions