【发布时间】:2015-04-10 12:02:07
【问题描述】:
我正在使用以下 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>
</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,但它不是。
但是我不明白模板匹配已经被很好地使用到能够弄清楚如何做到这一点。甚至可以在一个模板中满足这一要求吗?
【问题讨论】:
-
您的预期输出绝对正确吗?不应该关闭 123456 的行吗?
-
你是对的,谢谢。编辑修复。
-
@BenL 请不要编辑 OP 的代码 - 你不知道它是什么样子的。
-
@BenL 向我建议了编辑,我同意了,假设编辑只是缩进。
-
大多数时候缩进无关紧要,但有时它会有所作为。最好不要触碰原始代码(尤其是在发布依赖于原始代码的答案之后)。