问题
I'm using webpack as the bundler for a app and using an XML file for it configuration. Currently I'm writing tests to retrieve the config from an XML file packaged by webpack.
Referencing this webpack article: Loading data the piece of code I'm having trouble is this:
import Data from './data.xml';
I'm my own test, I'm using the require form which is as follows:
const select = require('xpath.js');
const DOMParser = require('xmldom').DOMParser
const parser = new DOMParser();
const data = require('./app.config.xml'); // <- THIS IS MY PROBLEM
const xdocument = parser.parseFromString(data.toString(), 'text/xml');
How does 'require' work for an XML file?
This code:
console.log("DATA: " + data.toString());
produces this output:
DATA: [object Object]
So I don't know what object is being created by the require.
I have seen a lot of other code samples about reading xml into JSON, but I don't what to have to handle a JSON object. I want to interrogate the XML as an XMLObject so can run xpath queries against it.
I can easily, get to the JSON, by running
JSON.stringify(data)
which displays something like:
{"Application":{"$":{"name":"config-data"},"Imports":[{"Import":[{"$":{"from":"./another.config.xml"}}]}],"Con
which is not what I want. So how can I get the XML content from *data* as a string, which is what **parser.parseFromString** needs?
My test code is as follows:
describe.only('xpath examples (zenobia)', async assert => {
const xdoc = require('./app.config.xml');
let applicationNodes = select(xdoc, "/Application"); // THIS RETURNS a DOMObject
console.log(`Found ${applicationNodes.length} Application elements`);
assert({
given: 'an inline xml document with an Application',
should: 'Select an element from the root',
condition: applicationNodes !== null
});
});
That log message displays:
Found 0 Application elements
for an XML document that is:
<?xml version="1.0"?>
<Application name="app">
<Imports/>
</Application>
回答1:
If you want to read XML files as strings you can simply use Webpack raw-loader with the following confiuration
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.xml$/i,
use: 'raw-loader',
},
],
},
};
Now data
in
const data = require('./app.config.xml');
Should be the raw data from the XML file (i.e. a string) - the rest of your code should now work as expected
来源:https://stackoverflow.com/questions/55172425/how-to-require-an-xml-file-loaded-by-webpack-in-order-to-read-the-xml-conten