-1

I am converting an object to an xml with nodejs. I want to add a comment <!-- My personal comment --> to the xml. I tried this code but createComment is always undefined.

const xml2js = require('xml2js');
const parser = new xml2js.Parser();
const builder = new xml2js.Builder();

 const parser = new xml2js.Parser();

 parser.parseString(body, (e, myobject) => {
 myobject.test = "test";
const xml = builder.buildObject(myobject);
//NOT WORKING var c = builder.createComment("My personal comment");
//NOT WORKING var c = xml.createComment("My personal comments");
xml.appendChild(c);
yalpsideman
  • 23
  • 2
  • 6

1 Answers1

1

xml2js is a tool for converting between JavaScript objects and XML.

It does not generate a DOM. It has no mechanism for creating comments (which aren't a feature of JavaScript objects).

buildObject returns a string of XML. It doesn't have an appendChild method because it is a string, not a document.

If you want to manipulate the XML with a DOM interface, then you'll need to parse it with an XML library that provides a DOM interface. For example: libxmljs.

const xml2js = require('xml2js');
const builder = new xml2js.Builder();
const libxml = require("libxmljs");
const xml = builder.buildObject({foo: 1, bar: 2});
const xmlDoc = libxml.parseXml(xml);
const foo = xmlDoc.get('//foo');
const comment = new libxml.Comment(xmlDoc, "This is a comment");
foo.addChild(comment);
console.log("" + xmlDoc);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335