首页 > 解决方案 > 如何每次仅从具有可变字符长度的子字符串中获取最后 4 个字符

问题描述

我优化了 xml 的发票,我希望只有变量的最后 4 个字符。对于我收到的每张发票,该变量可以有不同长度的字符,但我只想得到最后 4 个字符。

我已经用子字符串代码尝试过了,但是我需要给出一个特定的长度,代码需要从中获取最后 4 个字符。

我使用的代码:

<xsl:template match="/">
   <xsl:for-each select="/x:Invoice">
      <xsl:if test="."><xsl:value-of select="substring(translate(cbc:Note,' ',''),27,4)"/></xsl:if>
   </xsl:for-each>
</xsl:template>

这是发票的代码:

<UBLVersionID>2.0</UBLVersionID>
<CustomizationID>1.0</CustomizationID>
<ProfileID>PowerOnline</ProfileID>
<ID>194545</ID>
<IssueDate>2019-05-16</IssueDate>
<InvoiceTypeCode>1</InvoiceTypeCode>
<Note>FB - bestelling voor HH7416</Note>
<TaxPointDate>2019-05-16</TaxPointDate>
<DocumentCurrencyCode>EUR</DocumentCurrencyCode>
<LineCountNumeric>7</LineCountNumeric>
<OrderReference>
<ID>Invoice of an supplier</ID>
<SalesOrderID>19538</SalesOrderID>
<IssueDate>2019-04-30</IssueDate>

预期的结果是 /x:Invoice/cbc:Note 的最后 4 个字符,所以 7416。注释有时可能是 FB - HH6464,所以我总是想要那个 cbc 的最后 4 个字符:Note

标签: xmlxsltxslt-1.0

解决方案


您可以string-length结合使用substring来获取最后 4 个字符

<xsl:value-of select="substring(cbc:Note, string-length(cbc:Note) - 3)" />

(所以,doingstring-length(cbc:Note)会得到最后一个字符,string-length(cbc:Note) - 1会得到最后 2 个字符,依此类推......)


推荐阅读