0

我正在使用 create-react-app 构建一个简单的反应应用程序,我需要从该 xml 读取数据并在 UI 中显示。我已经尝试了几乎所有的 XML 转换包,例如 xml2js、xmltojson 流、xml-js、xml2json,但都失败了。xml2js 我已经尝试过将小 xml 转换为 json 但是当我尝试我的 xml 时它失败并出现错误:

Error: Unquoted attribute value
Line: 0
Column: 40401
Char: &
    at error (sax.js:651)
    at strictFail (sax.js:677)
    at SAXParser.write (sax.js:1367)
    at Parser.exports.Parser.Parser.parseString (parser.js:323)
    at Parser.parseString (parser.js:5)
    at Object.<anonymous> (Sal.js:22)
    at __webpack_require__ (bootstrap ac9a14d02bd3405bc94c:555)
    at fn (bootstrap ac9a14d02bd3405bc94c:86)
    at Object.<anonymous> (App.js:6)
    at __webpack_require__ (bootstrap ac9a14d02bd3405bc94c:555)

我的 XML 有 2784 行长,结构如下:


    <response>
    <header>
    ..
    .
    .
    .
    </header>
    <branches>
    ..
    ..
    </branches>
    <Products>
    <product1>
    ..
    ..
    </product1>
    <product2>
    ...
    </product2>
    ...
    ...
    ...
    </Products>
    </response>

我可以将 xml 作为本地文件或本地变量读取,但不知何故,我需要访问所有 Products 字段详细信息才能在 UI 上显示。

My code
var convert = require('xml-js');
import fs from 'fs'

var xml2 = fs.readFileSync('./xmlText.xml', 'utf8');
var options = {ignoreComment: true, alwaysChildren: true};
var result = convert.xml2js(xml2, options); // or convert.xml2json(xml, options)
console.log(result);

Uncaught TypeError: _fs2.default.readFileSync is not a function
    at Object.<anonymous> (converter.js:25)
    at __webpack_require__ (bootstrap efc8124703a44966d7ce:555)
    at fn (bootstrap efc8124703a44966d7ce:86)
    at Object.<anonymous> (App.js:6)
    at __webpack_require__ (bootstrap efc8124703a44966d7ce:555)
    at fn (bootstrap efc8124703a44966d7ce:86)
    at Object.<anonymous> (index.js:3)
    at __webpack_require__ (bootstrap efc8124703a44966d7ce:555)
    at fn (bootstrap efc8124703a44966d7ce:86)
    at Object.<anonymous> (bootstrap efc8124703a44966d7ce:578)


if i declare xml as a variable i get below error:
sax.js:651 Uncaught Error: Invalid character in entity name
Line: 0
Column: 54128
Char:  
    at error (sax.js:651)
    at strictFail (sax.js:677)
    at SAXParser.write (sax.js:1491)
    at Object.module.exports [as xml2js] (xml2js.js:346)
    at Object.<anonymous> (converter.js:27)
    at __webpack_require__ (bootstrap 3a3dffa4ca814efe6ba5:555)
    at fn (bootstrap 3a3dffa4ca814efe6ba5:86)
    at Object.<anonymous> (App.js:6)
    at __webpack_require__ (bootstrap 3a3dffa4ca814efe6ba5:555)
    at fn (bootstrap 3a3dffa4ca814efe6ba5:86)
4

1 回答 1

0

当我在我的 xml 中替换了 ' 和 & 符号时,我已经实现了这一点。

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


var xml = '<myxml></myxml>'
var options = {ignoreComment: true, alwaysChildren: true};
var result = convert.xml2js(xml2, options); // or convert.xml2json(xml, options)
console.log(result);
于 2020-02-26T10:28:09.937 回答