0

I'm using reading in a .HTML snippet from the file system; it contains just <h1>Hulton Archive</h1>. Then I'm writing a new XML file which must contain that HTML snippet in a certain element. using XMLbuilder to build an XML file out of it. Here's what I have:

var fs = require('fs');
var xml2js = require('xml2js');
var builder = new xml2js.Builder();
var parseString = require('xml2js').parseString;
var result;

var inputFile = "html-snippet.html";
var outputFile = "test.xml";

fs.readFile(inputFile, "UTF-8", function (err, data) {
  if (err) {
    return console.log(err);
  }

  console.log(data);

  var obj = {name: "Super", Surname: "Man", age: data};

  var outputXML = builder.buildObject(obj);

  fs.writeFile(outputFile, outputXML, function(err) {
    if(err) {
      console.log(err);
    } else {
      console.log(outputFile + " was saved!");
    }
  });

});

The problem is that the HTML tags are encoded in the input file; changed from <h1>header</h1> into &lt;h1&gt;header&lt;/h1&gt;. I want to preserve the HTML tags instead of encoding them in the output file.

I have tried writing this file using both XMLbuilder (https://github.com/oozcitak/xmlbuilder-js) and xml2js (https://github.com/Leonidas-from-XIV/node-xml2js). It seems like both of them were encoding the HTML on the output file.

How can I get write out the XML file without encoding the HTML?

4

1 回答 1

0

使用npm install ent您可以在生成 XML 后解码 HTML。但是,这确实会生成“无效”的 XML。对于大多数人来说,CDATA 可能是更好的选择。

var fs = require('fs');
var xml2js = require('xml2js');
var builder = new xml2js.Builder();
var parseString = require('xml2js').parseString;
var decode = require('ent').decode;

var result;

var inputFile = "html-snippet.html";
var outputFile = "test.xml";

fs.readFile(inputFile, "UTF-8", function (err, data) {
  if (err) {
    return console.log(err);
  }

  console.log(data);

  var obj = {name: "Super", Surname: "Man", age: data};

  var outputXML = decode(builder.buildObject(obj));

  fs.writeFile(outputFile, outputXML, function(err) {
    if(err) {
      console.log(err);
    } else {
      console.log(outputFile + " was saved!");
    }
  });

});
于 2014-12-12T00:32:24.870 回答