vsraju
vsraju

Reputation: 93

XSL Transform: need all of the nodes from xml

I have an XML program in the following structure

<cd>
    <year>1985</year>
</cd>
<cd>
    <year>1987</year>
</cd>

and xsl program

<xsl:template match="/">
   <xsl:apply-templates/>
</xsl:template>
<xsl:template match="cd">

      <xsl:element name="Year">
         <xsl:value-of select="year">
      </xsl:element>

</xsl:template>

i am getting output as 1985

But i need to get output as 1985 1987

How I can do that?? Somebody can help me with this...

Upvotes: 0

Views: 40

Answers (2)

Daniel Haley
Daniel Haley

Reputation: 52858

If your XML was well formed and truly as simple as shown, you could just do this...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>

    <xsl:template match="/*">
        <xsl:value-of select="normalize-space()"/>
    </xsl:template>

</xsl:stylesheet>

It wouldn't work if your input XML was all on a single line though; it would appear as 19851987 with no space. You could do something like this instead...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:strip-space elements="*"/>
    <xsl:output method="text"/>

    <xsl:template match="text()">
        <xsl:if test="preceding::text()">
            <xsl:text> </xsl:text>
        </xsl:if>
        <xsl:value-of select="."/>
    </xsl:template>

</xsl:stylesheet>

Upvotes: 1

Kokkie
Kokkie

Reputation: 556

If you want the output like you mentioned "1985 1987", give this a try;

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" version="1.0" encoding="UTF-8"/>
    <xsl:template match="/">
        <xsl:for-each select="//cd">
                <xsl:value-of select="year"/>
                <xsl:text> </xsl:text>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

More in the line with your approach you could select the tags, but this gives you an output with empty lines in between;

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" version="1.0" encoding="UTF-8"/>
<xsl:template match="/">
            <xsl:apply-templates select="//cd">
               <xsl:sort select="year"/>
            </xsl:apply-templates>
</xsl:template>
</xsl:stylesheet>

Upvotes: 0

Related Questions