如何使用 Webpack 加载器导入 XML 而不自动转换为 JSON [英] How to import XML using a Webpack loader WITHOUT automatic conversion to JSON
问题描述
Webpack 4 的 xml-loader 自动将导入的 XML 文件转换为 JSON.
Webpack 4's xml-loader automatically converts imported XML files to JSON.
我可以通过什么方式在不转换为 JSON 的情况下导入 XML?
By what means can I import XML without conversion to JSON?
XML 数据将使用现有的、应用程序专用的 XML 解析器进行处理.
The XML data is to be processed using an existing, application-dedicated XML parser.
明确地说,我绝对不希望以 JSON 格式加载结果.
To be clear, I definitely do not want the loaded result in JSON format.
推荐答案
结果证明是相对简单的,如果没有很好的文档记录.
It turned out to be relatively straightforward, if not so well documented.
基本上,我们依赖于 raw-loader,所以(使用 pnpm 来避免模块重复):
Basically, we rely on raw-loader, so (using pnpm to avoid module duplication):
pnpm install --save-dev raw-loader
在你的 webpack 配置文件中:
in your webpack config file:
rules: [
{ test: /\.xml$/,
use: [
'raw-loader'
]
},
:
我将在这里使用 d3.js(更具声明性,因此简洁).
I'm going to use d3.js here (more declarative, hence concise).
解析 xml 的方式因应用程序而异.在这里,我展示了处理 MusicXML 格式文件的第一步,其中乐谱采用部分格式.
The way you dissect your xml differs from application to application. Here I show the first step in processing a file in MusicXML format, with the score in partwise format.
一旦你有了顶级标签,你就可以开始挖掘了.其他 xml 格式有自己的专用标签 - 您需要在代码中研究和解决这些标签.
Once you have the top-level tag, you can start burrowing down. Other xml formats have their own dedicated tags - which you will need to research and address in your code.
import * as d3 from 'd3';
import score from '!!raw-loader!./path-to-file.xml';
var parser = new DOMParser();
var score_as_xml = parser.parseFromString(score, "application/xml");
// Could use d3.select(), as should only be one "score-partwise" occurrence:
var score_partwise_tag = d3.selectAll(score_as_xml.getElementsByTagName("score-partwise"));
if ((score_partwise_tag .. and so on.
这篇关于如何使用 Webpack 加载器导入 XML 而不自动转换为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!