Node JS的SQL外化(XML解析)

时间:2015-03-18 19:43:03

标签: javascript xml node.js parsing

假设我有以下文件:

<sql-requests>
  <sql-request id="insert_product"><![CDATA[INSERT INTO products]]></sql-request>
  <sql-request id="insert_account"><![CDATA[INSERT INTO accounts]]></sql-request>
  <sql-request id="insert_news"><![CDATA[INSERT INTO news]]></sql-request>
</sql-requests>

我想在节点中解析这个xml,然后像这样访问CDATA:

var sql = parsedXml.insert_product; // must return 'INSERT INTO products

最好的方法是什么?我应该根据自己的喜好选择哪个套餐?我找不到一个可以读取CDATA值的包。

回答(非常感谢Felix提供了如何做到这一点的想法)

var parseString = require('xml2js').parseString;
var fs = require('fs');
var content = fs.readFileSync(__dirname + '/sql-requests.xml');

var sql = {};

parseString(content, function (err, result) {

var queries = result['sql-requests']['sql-request'];

queries.forEach(function(query){
    var id = query.$.id, request = query._.trim();
    sql[id] = request;
});

});

现在,sql["insert_product"]将返回INSERT INTO products

2 个答案:

答案 0 :(得分:1)

var parseString = require('xml2js').parseString;
var xml = '<sql-requests>' +
'<sql-request id="insert_product"><![CDATA[INSERT INTO products]]></sql-request>' +
'<sql-request id="insert_account"><![CDATA[INSERT INTO accounts]]></sql-request>' +
'<sql-request id="insert_news"><![CDATA[INSERT INTO news]]></sql-request>' +
'</sql-requests>';

// Prints: '"INSERT INTO products"'
parseString(xml, function (err, result) {
  console.dir(JSON.stringify(result['sql-requests']['sql-request'][0]._));
});

答案 1 :(得分:1)

我不知道是否有一个XML解析器可以创建id -> element映射,但xml2js肯定适用于CDATA部分,您可以自己轻松创建这样的映射,假设您的结构很简单如问题:

var parseString = require('xml2js').parseString;

parseString(xml, function (err, result) {
  var queries = result['sql-requests']['sql-request'].reduce(queries, query) {
      queries[query.$.id] = query._;
      return queries;
  }, {});
  // queries is not an id -> content map
});