XSL text output - trim blank lines and leading spaces

I have an XSLT that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" indent="no" encoding="utf-8" media-type="text/plain" />
    <xsl:template match="/SOME/NODE">
        <xsl:if test="./BLAH[foo]">
<xsl:value-of select="concat(@id, ',' , ./BLAH/bar/@id, ',' , ./blorb/text())"/>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

The output looks something like this (it is going to be a CSV file):



    1,2,3
    4,456,22

    90,5,some text


    365,16,soasdkjasdjkasdf
    9,43,more text

What I need is for it to be transformed into:

1,2,3
4,456,22
90,5,some text
365,16,soasdkjasdjkasdf
9,43,more text

The main problems are the blank lines (from nodes that do not match the IF condition) and the indentation. Is there any way to remove the blank lines and trim the indentation while preserving the line breaks after lines that are not blank?

I've tried using <xsl:strip-space elements="*"/>, but then the output looks like this:

1,2,3,4,456,22,90,5,some text,365,16,soasdkjasdjkasdf,9,43,more text

Which doesn't work since I need to have 3 values on each line.

As requested, a (heavily simplified) sample of the input:

<SOME>
    <NODE>
        <BLAH id="1">
            <foo>The Foo</foo>
            <bar id="2" />
            <blorb> some text </blorb>
        </BLAH>
    </NODE>
    <NODE>
        <BLAH id="3">
            <bar id="4" />
            <blorb>some text that shouldn't be in output because there's no foo here</blorb>
        </BLAH>
    </NODE>
    <NODE>
        <BLAH id="5">
            <foo>another Foo</foo>
            <bar id="6" />
            <blorb>some other text</blorb>
        </BLAH>
    </NODE>
</SOME>

Upvotes: 0

Views: 748

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117073

I would suggest you approach it this way:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"  encoding="utf-8" />

<xsl:template match="/SOME">
    <xsl:for-each select="NODE/BLAH[foo]">
        <xsl:value-of select="@id"/>
        <xsl:text>,</xsl:text>
        <xsl:value-of select="bar/@id"/>
        <xsl:text>,</xsl:text>
        <xsl:value-of select="blorb"/>
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions