Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import XML using a Webpack loader WITHOUT automatic conversion to JSON

Tags:

xml

webpack-4

Webpack 4's xml-loader automatically converts imported XML files to JSON.

By what means can I import XML without conversion to JSON?

The XML data is to be processed using an existing, application-dedicated XML parser.

To be clear, I definitely do not want the loaded result in JSON format.

like image 770
user1019696 Avatar asked Jul 05 '26 21:07

user1019696


1 Answers

It turned out to be relatively straightforward, if not so well documented.

Basically, we rely on raw-loader, so (using pnpm to avoid module duplication):

pnpm install --save-dev raw-loader

in your webpack config file:

rules: [
  { test: /\.xml$/,
    use: [
      'raw-loader'
    ]
  },

I'm going to use d3.js here (more declarative, hence concise).

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.

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.
like image 198
user1019696 Avatar answered Jul 07 '26 12:07

user1019696