用于CSV转换的XSLT模板匹配

时间:2015-04-10 12:02:08

标签: xml csv xslt

我使用以下XSL将XML转换为CSV,基于早期的SO查询。

XML:

<Rows>
<Row>
<LoanNumber>123456</LoanNumber>
<DateReceived>2015-04-10</DateReceived>
<DateClosed>2015-04-10</DateClosed>
</Row>
<Row>
<LoanNumber>9988776</LoanNumber>
<DateReceived>2015-04-10</DateReceived>
<DateClosed/>
</Row>
</Rows>

XSL:

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

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

<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() = 1"><xsl:value-of select="normalize-space(.)"/>,OPEN,</xsl:if>
<xsl:if test="position() != 1 and position() != last()"><xsl:value-of select="normalize-space(.)"/>,</xsl:if>
<xsl:if test="position()  = last()"><xsl:value-of select="normalize-space(.)"/><xsl:text>&#xD;</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>

我希望能够为上述行输出以下CSV

123456, CLOSED, 2015-04-10, 2015-04-10
9988776, OPEN, 2015-04-10,

我假设我可以通过2个模板来实现这一点,一个输出文本OPEN,其中<DateClosed>元素为空,一个输出文本CLOSED,而不是。

但是,我并不了解模板匹配已被充分利用以便能够弄清楚如何执行此操作。甚至可以在一个模板中满足此要求吗?

1 个答案:

答案 0 :(得分:2)

您的输出与您的输入不符。假设您希望显示结果 LoanNumber,Status,DateReceived,DateClosed我建议你这样试试:

XSLT 1.0

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

<xsl:template match="/Rows">
    <xsl:for-each select="Row">
        <xsl:value-of select="LoanNumber"/>
        <xsl:text>,</xsl:text>
        <xsl:choose>
            <xsl:when test="string(DateClosed)">CLOSED,</xsl:when>
            <xsl:otherwise>OPEN,</xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select="DateReceived"/>
        <xsl:text>,</xsl:text>
        <xsl:value-of select="DateClosed"/>
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>