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

在GAS(Google Apps Script)中如何将XML路径拆分为数组

优化实现方案

你原来的实现依赖固定截取首尾字符,一旦输入路径存在首尾空白、标签带属性、或者有冗余字符的情况就会出错,用正则匹配所有标签名的方案兼容性会好很多:

function GetPathArray(path) {
  if (path == null) return null
  // 匹配所有尖括号内的标签名,自动过滤闭合标记、属性等冗余内容
  const matchResult = path.match(/(?<=<)[^<>/]+(?=>)/g)
  return matchResult ?? []
}

这个方案的优势:

  • 不需要硬截取字符串长度,不会因为输入长度异常出错
  • 即使输入存在标签属性、首尾空白、少量格式瑕疵,只要标签结构完整就能正常提取
  • 输入<product><containeditem><productidentifier>测试时,直接返回['product', 'containeditem', 'productidentifier'],完全符合预期

如果你能确定业务场景中输入的XML路径不会带属性、也不会有格式异常,也可以用更轻量的字符串处理方案:

function GetPathArray(path) {
  if (path == null) return null
  return path.replace(/[<>]/g, '').split('/').filter(Boolean)
}

内容的提问来源于stack exchange,提问作者Malte K.oder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 15:45:04