Home > Software design >  XML and XSLT results separated with commas
XML and XSLT results separated with commas

Time:09-19

I am using the xslt language to transform an xml document. The result that I am getting at the moment is not exactly what I want to achieve. I want to be able to get an xml format result separated with commas. I want my result to be in this correct way with returned values separated with commas.

<caller>1013, Product Enquiry, Courrier, Mobile Phone, Undecided</caller>

But what I am getting at the moment is wrong and it is this one below. 1013Product EnquiryCourrierMobile PhoneUndecided

This is my caller.xml file.

<caller>
    <number message="id">1013</number>
    <number message="voice">Product Enquiry</number>
    <number message="delivery">Courrier</number>
    <number message="device">Mobile Phone</number>
    <number message="subscription">Undecided</number>
</caller>

This is my xslt caller.xsl file.

<xsl:template match="/" priority="0">
    <xsl:if test="position()>2">
        <xsl:text>, </xsl:text>
    </xsl:if>
    <xsl:apply-templates/>
    <caller>
        <xsl:apply-templates select="caller/number">              
        </xsl:apply-templates>
    </caller>    
</xsl:template>```

I am getting two results with this xslt code and none of them has commas in it. I will appreciate if some can point me int he right direction to fix it.

CodePudding user response:

The result you want can be produced quite easily using:

XSLT 1.0

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

<xsl:template match="/caller">
    <xsl:copy>
        <xsl:for-each select="number">
            <xsl:value-of select="."/>
            <xsl:if test="position() != last()">, </xsl:if>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Or, if your processor supports it:

XSLT 2.0

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

<xsl:template match="/caller">
    <xsl:copy>
        <xsl:value-of select="number" separator=", "/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
  • Related