我不希望在最后一个元素xslt之后有一个尾随逗号

时间:2015-02-27 21:11:24

标签: xml xslt

在我的架构中,我有AddressLine1,AddressLine2,AddressLine3和AddressLine4。将地址添加到每个AddressLine时,将插入逗号以分隔AddressLines。但是,如果只有AddressLine1和AddressLine2有地址,那么AddressLine2后面不应该有逗号,因为之后没有其他内容。 我的输出在AddressLine2(悉尼澳大利亚123456A)之后显示一个尾随逗号,即使它不应该。 产量 472 Case Ave,Apt 2,Saint Paul,MN,55106; 123 Beautiful Ocean,Sydney Australia 123456A,

Xml代码

<Address InternalAddressID="1618212014" Type="Foreign">
    <Location Word="OTHER">Other</Location>
    <AddressLine1>123 Beautiful Ocean</AddressLine1>
    <AddressLine2>Sydney Australia 123456A</AddressLine2>
    <Foreign>true</Foreign>
</Address>

Xslt代码

<xsl:for-each select="Addresses/Address">
<xsl:for-each select="ancestor::ProtectionOrder/ProtectionOrderParties/ProtectionOrderParty/MNProtectionOrderPartyAdditional/ProtectedAddresses/Address[@InternalAddressID=current()/@InternalAddressID]">
<xsl:if test="AddressLine1">
<xsl:value-of select="AddressLine1"/>
<xsl:text>, </xsl:text>
</xsl:if>
<xsl:if test="AddressLine2">
<xsl:value-of select="AddressLine2"/>
<xsl:text>, </xsl:text>
</xsl:if>
<xsl:if test="AddressLine3">
<xsl:value-of select="AddressLine3"/>
<xsl:text>, </xsl:text>
</xsl:if>
<xsl:if test="AddressLine4">
<xsl:value-of select="AddressLine4"/>
</xsl:if>
<xsl:text>; </xsl:text>
</xsl:for-each>
</xsl:for-each>

2 个答案:

答案 0 :(得分:0)

只需使用

<xsl:for-each select="AddressLine1 | AddressLine2 | AddressLine3 | AddressLine4">
  <xsl:if test="position() > 1">, </xsl:if>
  <xsl:value-of select="."/>
</xsl:for-each>

答案 1 :(得分:0)

我建议你将策略改为:

<xsl:template match="Address">
    <xsl:apply-templates select="AddressLine1 | AddressLine2 | AddressLine3 | AddressLine4"/>
</xsl:template> 

<xsl:template match="AddressLine1 | AddressLine2 | AddressLine3 | AddressLine4">
    <xsl:value-of select="."/>
    <xsl:if test="position()!=last()">, </xsl:if>
</xsl:template>  

或者,在您使用 XSLT 2.0 的机会中:

<xsl:template match="Address">
    <xsl:value-of select="AddressLine1 | AddressLine2 | AddressLine3 | AddressLine4" separator=", "/>
</xsl:template>