anurag
anurag

Reputation: 137

how to output text inside an xml tag using xslt

i have an xml file where scenario is something like this

<heading inline='true'>
 HELLO
</heading>
  <abc>
     <p>WORLD</p>
     <p>NEW LINE1</p>
     <p>NEW LINE2</p>
     <p>NEW LINE3</p>
  </abc>

i need to output

HELLO WORLD$TNEW LINE1$TNEW LINE2$TNEW LINE3

using xslt.

The rule is, if there is a heading tag with inline attribute true preceding to p tag , first p tag needs to be output with a space and rest all other p tags needs to be output with $T .

What i have tried :-

<xsl:template match="p">
<xsl:choose>
 <xsl:when test="preceding::heading[@isInline= 'true'] and not(preceding::p)"> 
  <xsl:text> </xsl:text>
  <xsl:when>

  <xsl:otherwise>
   <xsl:text>$T</xsl:text>
  </xsl:otherwise>
    </xsl:choose>

<xsl:apply-templates/>
</xsl:template>

but there are many heading tag preceding p and my snippet is accounting for all heading tags preceding p. I want to consider the heading tag just preceding p. Also there can be many level of nesting in tags to i cannot use a relative xpath involving abc and sibling

i am using xslt 2.0 and output method is text

Any inputs would be of great help

Upvotes: 0

Views: 1794

Answers (1)

Joel M. Lamsen
Joel M. Lamsen

Reputation: 7173

try the following stylesheet below:

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

    <xsl:strip-space elements="*"/>

    <xsl:output method="text"/>

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

    <xsl:template match="p">
        <xsl:choose>
            <!-- test for the first preceding node named heading, with an inline attribute equal to true -->
            <xsl:when test="preceding::*[1][name()='heading'][@inline= 'true']">
                <xsl:text> </xsl:text>
            </xsl:when>
            <xsl:otherwise>
                <xsl:text>$T</xsl:text>
            </xsl:otherwise>
        </xsl:choose>
        <xsl:apply-templates/>
    </xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions