0

I've tried to use xml-js and xml2js but both are returning the same error.

<?xml version="1.0" encoding="UTF-8"?>
^

SyntaxError: Unexpected token <
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)

The xml example:

<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

The code example:

var notes =require('./test.xml')

var convert = require('xml-js');
var xml =notes;

var result1 = convert.xml2json(xml, {compact: true, spaces: 4});
var result2 = convert.xml2json(xml, {compact: false, spaces: 4});

console.log(result1, '\n', result2);

Can you help with the solution to this? I've tried using JSON.parse, JSON.stringify but it is not working anyways.

I'm trying to parse an XML to convert to JSON, by the way.

1 Answer 1

5

The issue isn't with the XML parsing, it's with the fact you're using require, which loads Node.js module for reading another file. Instead, you should use a simple file reading method, such as fs.readSync:

fs = require('fs');
var notes = fs.readFileSync('./test.xml')
Sign up to request clarification or add additional context in comments.

11 Comments

@spaceman: Recheck your work: readFileSync() would not yield the same error.
@spaceman please post the full code and the error you're getting. Your snippet has a mistake later on where you use mNotes instead of notes, but other than that, it works on my machine.
@Mureinik the error and the code is in the question, didn't change. Ive corrected this mistake you've noticed minute after posting it.
@spaceman: It's not about the ||. It's about you failing to extract a true minimal reproducible example. Until you do that, we can't help you without guessing about the rest of your context, and that's extremely inefficient.
@spaceman: The three lines of code alone you posted with readFileSync() simply do not yield the error you posted. You're wasting everyone's time by not posting a complete MCVE. Until you narrow the problem properly, you'll have a hard time figuring out your problem or getting help from others. Moving on. Good luck.
|

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.