Home > OS >  xsltproc XML parser multi value
xsltproc XML parser multi value

Time:03-26

I'm using xsltproc to parse XML content into text content. Need to separate multiple values for one tag.

My XML:

<data xml:space="preserve" id="USER">
    <c1>USER NAME</c1>
    <c2>ADDRESS</c2>
    <c3>DET</c3>
    <c4>AILS</c4>
    <c5>1001</c5>
    <c5 a="2">2001</c5>
    <c5 a="3">3001</c5>
    <c5 a="4">401</c5>
    <c5 a="5">5001</c5>
    <c5 a="6">6001</c5>
    <c6>1</c6>
    <c7>20991231M0601</c7>
</data>

My xsl:

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

<!-- write out comma separated file -->
<xsl:template match="data">
        <xsl:value-of select="c1"/>
        <xsl:value-of select="','"/>
        <xsl:value-of select="c2"/>
        <xsl:value-of select="','"/>
        <xsl:value-of select="c3"/>
        <xsl:value-of select="','"/>
        <xsl:value-of select="c4"/>
        <xsl:value-of select="','"/>
        <xsl:apply-templates select="c5"/>
        <xsl:value-of select="','"/>
        <xsl:value-of select="c6"/>
        <xsl:value-of select="','"/>
        <xsl:value-of select="c7"/>
        <xsl:value-of select="','"/>
        <xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>

Post execution, My output comes like,

USER NAME,ADDRESS,DET,AILS,10012001300140150016001,1,20991231M0601,

But i wanted an output like

USER NAME,ADDRESS,DET,AILS,1001|2001|3001|401|5001|6001,1,20991231M0601, With separator for the multi value.

CodePudding user response:

How about:

XSLT 1.0

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

<xsl:template match="data">
    <xsl:for-each select="c1|c2|c3|c4">
        <xsl:value-of select="."/>
        <xsl:text>,</xsl:text>
    </xsl:for-each> 
    <xsl:for-each select="c5">
        <xsl:value-of select="."/>
        <xsl:if test="position()!=last()">|</xsl:if>
    </xsl:for-each>
    <xsl:text>,</xsl:text>
    <xsl:value-of select="c6"/>
    <xsl:text>,</xsl:text>
    <xsl:value-of select="c7"/>
    <xsl:text>&#10;</xsl:text>
</xsl:template>

</xsl:stylesheet>
  • Related