0
我有一個XML文件,我需要用來自數組的值使用GulpJS替換屬性值。數組users1中的現有屬性值需要用users2數組中的項替換。如何使用gulpjs將數組值替換爲另一個數組中的值
JavaScript代碼:
var gulp = require('gulp');
var replace = require('gulp-replace');
var rs = require('replacestream');
var through = require('through2');
gulp.task('default', function() {
//array is dynamic
var users1 = ["existing_value1", "existing_value2", "existing_value3"];
var users2 = ["new_value1", "new_value2", "new_value3"];
var num = users.length();
gulp.src(['idmap/*.xml'])
.pipe(replaceArray(users1, users2))
.pipe(gulp.dest('build/'));
});
function replaceArray(searchArray, replacement) {
return through.obj(function(file, encoding, callback) {
if (file.isBuffer()) {
var result = searchArray.reduce(function(contents, searchArray) {
return contents.split(searchArray).join(replacement);
}, String(file.contents));
file.contents = new Buffer(result);
return callback(null, file);
}
callback(null, file);
});
}
示例XML:
<?xml version="1.0"?><IDMAP>
<RECORD>
<TOKEN data="414" />
<NAME data="existing_value1" />
</RECORD>
<RECORD>
<TOKEN data="420" />
<NAME data="existing_value2" />
</RECORD>
<RECORD>
<TOKEN data="361" />
<NAME data="existing_value3" />
</RECORD></IDMAP>
利用上述代碼中,我發現了在XML中的所有值(用戶1陣列)由在逗號分隔值替換users2數組。如何用數組中的相應元素替換所有項目?
提前致謝!
謝謝@sven! (i = 0; i