【问题标题】:GulpJS - how to read value from xml file and add it to a json file?GulpJS - 如何从 xml 文件中读取值并将其添加到 json 文件中?
【发布时间】:2016-03-18 18:39:27
【问题描述】:

我对 Gulp/Node 编程有点菜鸟,我正在努力做一个简单的任务:)

我有一个 XML 文件,其中包含这样的节点:<widget version="1.1"></widget>

我想读出版本值并将该值放入 json 文件中。这是如何实现的?

这是我尝试过的:

var configXml      = 'config.xml';
var enTemplateJson = 'signing/en_template.json';

代码

脚本

return gulp.src([configXml])
          .pipe(cheerio({
            parserOptions: {
              xmlMode: true
            },
            run: function($, file) {
              $('widget').each(function() {
                var version = $(this)[0].attribs.version;

                // prints version 1.1
                console.log(version);
              })
            }
          }))
          .pipe(gulp.dest('test.xml'));

【问题讨论】:

  • 您遇到的具体问题是什么
  • 我需要从 XML 文件中读取版本值并将其写入 JSON 文件。除非有办法同时打开两个文件,否则我无法在 gulp 中实现这一点?
  • en_template.json 文件是您需要使用来自config.xml 的版本修补的现有 json 文件吗?或者您可以每次都重新创建它吗?

标签: javascript json xml node.js gulp


【解决方案1】:

我想通了:

// App Versioning
gulp.task('update-version', function() {
  // Read config.xml file synchronously
  var xml       = fs.readFileSync('./config.xml');

  // Use cheerio to parse the xml and extract the version number
  var $         = cheerio.load(xml, { xmlMode: true });
  var version   = $('widget')[0].attribs.version;

  return gulp.src('signing/en.json')
          .pipe(replace(/\${APP_VERSION}/, version))
          .pipe(gulp.dest('app/i18n'));
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多