0

I am new to javascript and node and I would need to send some data into a DB. The data is coming from an xml file.

I am trying to use xml2js package, building slowly from the example given, and adding attributes into the xml.

Here is the code:

var parseString = require('xml2js').parseString;
const options = {
    explicitArray: false
};
var xml = "<root><level1>Hello xml2js!</level1><level2>How are things?</level2></root>"
parseString(xml, options, function (err, result) {
    console.dir(result);
});

This works and gives the expected result: { root: { level1: 'Hello xml2js!', level2: 'How are things?' } }

However, if I try to add attributes, for instance: var xml = "<root><level1 id="1">Hello xml2js!</level1><level2>How are things?</level2></root>" which starts resembling the file I will have to work with, I receive an error.

What am I missing? Thanks!

Edit: The error I am getting is:

var xml = "<root><level1 id="1">Hello xml2js!</level1><level2>How are things?</level2></root>"
                             ^

SyntaxError: Unexpected number
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
    at node:internal/main/run_main_module:23:47

Node.js v19.0.1
zukato
  • 1
  • 2

1 Answers1

0

I tried the following and it worked for me

  1. Comment out or remove the
explicitArray: false 

line in the options object and then

  1. log using the following
console.dir(result.root.level1[0].$.id)

You should get back '1'. If you just log result you should get back

{ root: { level1: [ [Object] ], level2: [ 'How are things?' ] } }
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
DeanF
  • 1
  • 1