意外的令牌 <在 NodeJS 中解析 XML 时 [英] Unexpected token < when parsing XML in NodeJS

查看:27
本文介绍了意外的令牌 <在 NodeJS 中解析 XML 时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 xml-jsxml2js 但都返回相同的错误.>

<?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)

xml 示例:

<?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>

代码示例:

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);

你能帮忙解决这个问题吗?我试过使用 JSON.parse, JSON.stringify 但它无论如何都不起作用.

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

顺便说一下,我正在尝试解析 XML 以转换为 JSON.

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

推荐答案

问题不在于 XML 解析,而在于您正在使用加载 Node.js 模块的 require用于读取另一个文件.相反,您应该使用简单的文件读取方法,例如 fs.readSync:

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')

这篇关于意外的令牌 &lt;在 NodeJS 中解析 XML 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆