我将webpack用作应用程序的捆绑程序,并使用XML文件进行配置。目前,我正在编写测试以从webpack打包的XML文件中检索配置。
请参阅此Webpack文章:Loading data我遇到麻烦的这段代码是:
import Data from './data.xml';
我是我自己的考试,我使用的是 require 表格,如下所示:
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');
“需要”如何处理XML文件?
此代码:
console.log("DATA: " + data.toString());
产生以下输出:
DATA: [object Object]
所以我不知道需求正在创建什么对象。
我已经看到了许多其他有关将xml读入JSON的代码示例,但是我不需要处理JSON对象。我想将XML作为XMLObject进行查询,以便可以对它运行xpath查询。
我可以通过运行
轻松获取JSON。JSON.stringify(data)
显示如下内容:
{"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?
我的测试代码如下:
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
});
});
该日志消息显示:
Found 0 Application elements
对于以下XML文档:
<?xml version="1.0"?>
<Application name="app">
<Imports/>
</Application>
答案 0 :(得分:1)
如果您想将XML文件读取为字符串,则可以使用Webpack raw-loader并进行以下配置
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.xml$/i,
use: 'raw-loader',
},
],
},
};
现在
中的data
const data = require('./app.config.xml');
应该是XML文件(即字符串)中的原始数据-您的其余代码现在应该可以按预期工作了