如何使用 XPath 查询仅检索字符串中的最后 4 个字符

问题描述 投票:0回答:4

我正在使用 xpaths 从 XML 格式的文件中检索各种数据点。

有一种情况,我只想提取一个值的最后 4 位数字,但我不知道如何提取。

我测试了该网站上找到的各种子字符串方法,但没有一个起作用。

<TAXPAYER_IDENTIFIERS>
     <TAXPAYER_IDENTIFIER SequenceNumber="1">
         <TaxpayerIdentifierType>SocialSecurityNumber</TaxpayerIdentifierType>
         <TaxpayerIdentifierValue>123456789</TaxpayerIdentifierValue>
     </TAXPAYER_IDENTIFIER>
</TAXPAYER_IDENTIFIERS>
xml xpath
4个回答
3
投票

有一种情况,我只想提取一个值的最后 4 位数字,但我不知道如何提取。

检索值的最后 4 位数字,例如

TaxpayerIdentifierValue
,您可以使用以下XPath-1.0表达式:

substring(/TAXPAYER_IDENTIFIERS/TAXPAYER_IDENTIFIER/TaxpayerIdentifierValue, string-length(/TAXPAYER_IDENTIFIERS/TAXPAYER_IDENTIFIER/TaxpayerIdentifierValue) - 4 + 1, 4)

它的输出是:

6789


0
投票

如果当前节点是TaxpayerIdentifierValue,只需调用

substring
并使用
string-length
计算子字符串的起始位置:

substring(., string-length(.) - 3)

从根源开始,做到了

substring(/TAXPAYER_IDENTIFIERS/TAXPAYER_IDENTIFIER/TaxpayerIdentifierValue,
          string-length(/TAXPAYER_IDENTIFIERS/TAXPAYER_IDENTIFIER/TaxpayerIdentifierValue) - 3)

0
投票

这是简单的 xpath。

//TaxpayerIdentifierValue/substring(., string-length(.) - 3)

这是输出截图:

您也可以使用下面的xpath。

//TaxpayerIdentifierValue/substring(text(), string-length(text()) - 3)


0
投票

有人可以解释一下 string-lenght()-3 是如何工作的吗?我无法弄清楚。

© www.soinside.com 2019 - 2024. All rights reserved.