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?

1

1 Answer 1

0

Using npm install ent you can decode the HTML after you generate the XML. This does generate "invalid" XML however. For most people, CDATA is probably the better choice.

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!");
    }
  });

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.