如何在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;
}
}

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

var path = '<product><containeditem><productidentifier>';
console.log( getPathArray(path) );
function getPathArray(path){
return path.slice(1, -1).split('><');
}

slice函数丢弃第一个和最后一个字符(开头和结尾的<>(。

那么split就是您所需要的全部,因为它返回一个数组。

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

答案

正如@andrewjames所说,解决方案取决于路径的外观。如果它像你的例子一样,你可以用JavaScript 的基本字符串方法得到解决方案

代码

function getPathArray(path){
path = path.split('><').join(', ')
path = path.replace('<','[')
path = path.replace('>',']')
return path
}

参考文献

  • String.protype.replacement((
  • String.protype.split((
  • Array.prototype.join((

最新更新