在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
相关产品推荐
相关产品推荐

