【发布时间】:2021-10-08 10:31:42
【问题描述】:
我正在尝试创建一个接受自定义 .xml 文件并使用 xml2json-ltx 库将其中的内容解析为 JSON 对象的 XML 到 JSON 转换器应用程序。我已经完成了解析/转换部分,但结果 JSON 有点难看。
我只想美化解析后的 JSON 并在生成的 JSON 对象中添加适当的缩进。我怎样才能?请用一个例子评论/回答:)
LtxParser.jsx
import React, { useState, useEffect } from "react";
import parser from "xml2json-ltx";
const Ltx = () => {
const [fileState, setFileData] = useState();
const [jsonData, setJsonData] = useState();
useEffect(() => {
if (!!fileState) {
const resultObj = parser.toJson(fileState, {
object: true,
});
setJsonData(resultObj);
}
}, [fileState]);
const onFileDrop = (e) => {
e.preventDefault();
const fileData = e.target.files[0];
const reader = new FileReader();
reader.onload = function (evt) {
setFileData(evt.target.result);
};
reader.readAsText(fileData);
};
return (
<div>
Ltx
<input type="file" onChange={onFileDrop} />
{jsonData && JSON.stringify(jsonData, undefined, 4)}
</div>
);
};
export default Ltx;
示例.xml
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
</book>
</catalog>
【问题讨论】: