xml XSLT 设置默认值时选择一个不可用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18665516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XSLT set default value when selected one is not available
提问by randombits
Is it possible to set a default value using <xsl:value-of>? I am attempting to produce JSON output with an XSLT stylesheet and certain fields might not be available during the processing stage. This leaves a null value which breaks the validity of the JSON document. Ideally I'd be able to set a default value if one is not available. So in the case of:
是否可以使用设置默认值<xsl:value-of>?我正在尝试使用 XSLT 样式表生成 JSON 输出,并且某些字段在处理阶段可能不可用。这会留下一个空值,这会破坏 JSON 文档的有效性。理想情况下,如果一个默认值不可用,我可以设置一个默认值。所以在以下情况下:
"foo_count": <xsl:value-of select="count(foo)" />
If <foo>is not available in the document, can I just set this to 0 somehow?
如果<foo>文档中不可用,我可以以某种方式将其设置为 0 吗?
回答by G. Ken Holman
XSLT/XPath 2
XSLT/XPath 2
Using Sequence Expressions:
使用序列表达式:
<xsl:value-of select="(foo,0)[1]"/>
Explanation
解释
One way to construct a sequence is by using the comma operator, which evaluates each of its operands and concatenates the resulting sequences, in order, into a single result sequence.
构造序列的一种方法是使用逗号运算符,它 计算每个操作数并将结果序列按顺序连接成单个结果序列。
回答by rene
It is either choose
要么选择
<xsl:choose>
<xsl:when test="foo">
<xsl:value-of select="count(foo)" />
</xsl:when>
<xsl:otherwise>
<xsl:text>0</xsl:text>
</xsl:otherwise>
</xsl:choose>
or use if test
或使用if 测试
<xsl:if test="foo">
<xsl:value-of select="count(foo)" />
</xsl:if>
<xsl:if test="not(foo)">
<xsl:text>0</xsl:text>
</xsl:if>
or use a named template for calling
或使用命名模板进行调用
<xsl:template name="default">
<xsl:param name="node"/>
<xsl:if test="$node">
<xsl:value-of select="count($node)" />
</xsl:if>
<xsl:if test="not($node)">
<xsl:text>0</xsl:text>
</xsl:if>
</xsl:template>
<!-- use this in your actual translate -->
<xsl:call-template name="default">
<xsl:with-param name="node" select="."/>
</xsl:call-template>
回答by édouard Lopez
XSLT/XPath 2.0
XSLT/XPath 2.0
You can use a Conditional Expressions (if…then…else)on your @selectexpression:
您可以在表达式if…then…else上使用条件表达式 ( )@select:
<xsl:value-of select="if (foo) then foo else 0" />

