首页 > 解决方案 > 如何在 GAS 中将 XML 路径拆分为数组

问题描述

搜索将 XML 路径拆分为数组的好方法。我觉得我的解决方案并不像我想要的那样可靠。

我有的:<product><containeditem><productidentifier>

我想要得到的是一个数组,如:[product, containeditem, productidentifier]

我的代码:

function GetPathArray(path) {
  if (path != null) {
    path = path.substring(0, path.length - 1);
    path = path.substring(1);

    var pathArray = [{}];

    pathArray = path.split("><");

    return pathArray;
  }
  else {
    return null;
  }
}

标签: xmlgoogle-apps-script

解决方案


为确保返回数组而不是字符串,您可以将其用于问题中的简单情况:

var path = '<product><containeditem><productidentifier>';

console.log( getPathArray(path) );

function getPathArray(path){
  return path.slice(1, -1).split('><');
}

slice函数丢弃第一个和最后一个字符(开始和结束<>)。

那么这split就是你所需要的 - 因为它返回一个数组。

对于更复杂的字符串,这几乎肯定是不够的。


推荐阅读