You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XPath中按固定宽度分割字符串?(X509证书Base64场景)

在XPath中按固定宽度分割Base64字符串(Xidel场景)

我用Xidel从SAMLResponse里提取//Assertion//Signature//KeyInfo//X509Certificate/text(),这是X509证书对应的长Base64字符串,想要将其分割为64字符的块。尝试tokenize()和replace()方法均未成功,具体问题如下:

一、replace()方法报错

使用replace()时,替换字符串中使用\n会触发错误,执行命令及错误信息如下:

执行命令:

echo "$SAMLRESPONSE" | base64 -D | xidel --xpath 'replace(//Assertion//Signature//KeyInfo//X509Certificate/text(),"(.{64})","$1\n")' -

错误输出:

**** Processing: stdin:/// ****
Error:
err:FORX0004: Invalid replacement: $1\n after $1\n
Possible backtrace:
  $000000010203F668: perhaps TXQTermTryCatch + 222920 ? but unlikely
  $0000000102068BBE: perhaps Q{http://www.w3.org/2005/xpath-functions}tokenize + 166350 ? but unlikely
  $000000010203FF78: Q{http://www.w3.org/2005/xpath-functions}replace + 376
  $0000000101FF853F: TXQTermNamedFunction + 767
  $0000000101F71CE7: perhaps ? ? but unlikely

Call xidel with --trace-stack to get an actual backtrace

二、tokenize()方法不符合需求

tokenize()会将匹配的64字符块视为分隔符,且分隔符不会包含在输出结果中,导致最终只输出剩余的不足64字符的部分:

执行命令:

echo "$SAMLRESPONSE" | base64 -D | xidel --xpath 'tokenize(//Assertion//Signature//KeyInfo//X509Certificate/text(),"(?:.{64})")' -

输出结果:

**** Processing: stdin:/// ****













XACcI5tcJbgsvr+ivGPos/WrhywkROwbEBh6OTNXTnaBiiIK

可行解决方案

方案1:修复replace()中的换行符处理

XPath的replace()函数不识别字符串中的\n转义符,需要使用实际的换行字符或通过codepoints-to-string(10)生成换行:

方法A:使用Shell转义换行(Bash环境)

echo "$SAMLRESPONSE" | base64 -D | xidel --xpath 'replace(//Assertion//Signature//KeyInfo//X509Certificate/text(),"(.{64})","$1'$'\n''")' -

方法B:使用XPath函数生成换行

echo "$SAMLRESPONSE" | base64 -D | xidel --xpath 'replace(//Assertion//Signature//KeyInfo//X509Certificate/text(),"(.{64})",concat($1, codepoints-to-string(10)))' -

方案2:用XPath循环截取子串

通过XPath 3.0的let表达式定义字符串,再循环截取每个64字符的块:

echo "$SAMLRESPONSE" | base64 -D | xidel --xpath 'let $cert := //Assertion//Signature//KeyInfo//X509Certificate/text(), $length := string-length($cert) return for $i in 0 to floor(($length - 1) div 64) return substring($cert, $i*64 + 1, 64)' -

该方法会将每个64字符块作为独立输出项,默认以换行分隔,最后不足64字符的部分也会完整保留。

内容的提问来源于stack exchange,提问作者RubenLaguna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 00:09:23