问题描述
如何在不显式写入的情况下按特定顺序写入元素属性?
How do you write element attributes in a specific order without writing it explicitly?
考虑:
<xsl:template match="Element/@1|@2|@3|@4">
<xsl:if test="string(.)">
<span>
<xsl:value-of select="."/><br/>
</span>
</xsl:if>
</xsl:template>
属性应按1, 2, 3, 4
顺序出现.不幸的是,您不能保证XML中属性的顺序,它可能是<Element 2="2" 4="4" 3="3" 1="1">
The attributes should appear in the order 1, 2, 3, 4
. Unfortunately, you can't guarantee the order of attributes in XML, it could be <Element 2="2" 4="4" 3="3" 1="1">
因此上面的模板将产生以下内容:
So the template above will produce the following:
<span>2</span>
<span>4</span>
<span>3</span>
<span>1</span>
理想情况下,我不想测试每个属性是否有值.我想知道是否可以通过某种方式设置显示顺序?还是我需要显式地执行该操作并重复if测试,如下所示:
Ideally I don't want to test each attribute if it has got a value. I was wondering if I can somehow set an order of my display? Or will I need to do it explicitly and repeating the if test as in:
<xsl:template match="Element">
<xsl:if test="string(./@1)>
<span>
<xsl:value-of select="./@1"/><br/>
</span>
</xsl:if>
...
<xsl:if test="string(./@4)>
<span>
<xsl:value-of select="./@4"/><br/>
</span>
</xsl:if>
</xsl:template>
在这种情况下可以做什么?
What can be done in this case?
推荐答案
在前面的问题中,您似乎使用了XSLT 2.0,所以我希望这次也可以使用XSLT 2.0解决方案.
In an earlier question you seemed to use XSLT 2.0 so I hope this time too an XSLT 2.0 solution is possible.
顺序不是在模板的匹配模式中确定的,而是在执行xsl:apply-templates时确定的.因此(使用XSLT 2.0),您可以简单地按所需顺序编写一系列属性,例如<xsl:apply-templates select="@att2, @att1, @att3"/>
将按该顺序处理属性.
The order is not determined in the match pattern of a template, rather it is determined when you do xsl:apply-templates. So (with XSLT 2.0) you can simply write a sequence of the attributes in the order you want e.g. <xsl:apply-templates select="@att2, @att1, @att3"/>
will process the attributes in that order.
XSLT 1.0没有序列,只有节点集.要产生相同的结果,请按要求的顺序使用xsl:apply-templates
,例如:
XSLT 1.0 doesn't have sequences, only node-sets. To produce the same result, use xsl:apply-templates
in the required order, such as:
<xsl:apply-templates select="@att2"/>
<xsl:apply-templates select="@att1"/>
<xsl:apply-templates select="@att3"/>
这篇关于按特定顺序对属性进行排序以输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!