首页 > 解决方案 > 仅从 xml 文件中检索名称并将它们放入 JavaScript 中的数组中

问题描述

// https://www.w3schools.com/xml/simple.xml

// 我得到了上面的 xml 文件,其中包含菜单项名称以及其他内容(价格、卡路里等),我只需要使用 JavaScript 编码将名称放入数组中。我正在使用 repl.it,并且我已经将文件保存为 .xml 在我的程序一侧。我只需要知道如何仅将名称提取到数组中。例如,数组应如下所示:[Belgian Waffles、Strawberry Belgian Waffles,(等等)]。

// 此外,我需要将卡路里、价格和其他东西放在单独的数组中,但我确信如果我学会了如何为一件事制作数组,我也可以做其他数组。

// 过去,我编写了这段代码来从带有分数列表的文件中检索分数(从评论中打开 repl.it 链接以查看它的实际效果):

// This program uses a file which has 6 peoples scores to calculate and display the max., min., and ave. scores and also puts them in an array. The program reads the file, trims out the strings so only the numbers are left & converted to numbers, limits the average score to the hundreths place, and verifies the file exists. The number of scores can be changed from 6 and the program would still work.
// Reference(s): https://www.w3schools.com/jsref/jsref_tofixed.asp
// https://codeburst.io/javascript-arrays-finding-the-minimum-maximum-sum-average-values-f02f1b0ce332
// Repl.it link: https://repl.it/live/AFSloyKSNJQjlA

main();

function main() {
    var filename = "scores.txt";

    if(!fileExists(filename)) {
        console.log(`File ${filename} is missing.`)
        return
    }

    var scores = [];
    var scores = readFile("scores.txt");
    console.log(scores);

    var maximum = getMax(scores);
    console.log("Maximum score: " + maximum)

    var minimum = getMin(scores);
    console.log("Mininum score: " + minimum);

    var sum = getSum(scores);

    var ave = sum / scores.length;
    var ave = ave.toFixed(2);
    console.log("Average score: " + ave);
}

function fileExists(filename) {
    var fs = require('fs');
    return fs.existsSync(filename);
}

function readFile(filename) {
    var fs = require('fs');
    var scores = [];

    var contents = fs.readFileSync(filename, 'utf8');
    lines = contents.split('\n');

    for (var index = 0; index < lines.length; index++)  {
        var pos = lines[index].indexOf(',') + 1;
        var scoreStr = lines[index].substring(pos).trim();
        var score = Number(scoreStr);
        if (!isNaN(score)) {
          scores.push(score);
        }
    }

    return scores;
}

function getMax(scores) {
    scores.sort(function(a, b){return b - a});
    var maximum = scores[0];

    return maximum;
} 

function getMin(scores) {
    scores.sort(function(a, b){return a - b});
    var minimum = scores[0];

    return minimum;
}

function getSum(scores)  {
    return scores.reduce(function(a,b){
      return a + b
    }, 0);
}

标签: javascriptarraysxmlsplit

解决方案


有两种方法可以解决这个问题。如果您有一个需要运行的 XML 字符串,而您只需要单个标记类型的内容,则可以通过此正则表达式运行该字符串以获得所需的内容:

// xmlString is a string with the whole XML document in it
const foods = xmlString.match(/(?<=<name>)[A-Za-z ]+(?=<\/name>)/g);

如果你想通过遍历 XML DOM 得到它,你可以使用 JavaScript 的标准 DOM 操作工具,像这样:

const foodTagList = document.querySelectorAll('food name'); // selects all name nodes under food nodes
const foodList = [];
foodTagList.forEach((el) => foodList.push(el.innerHTML)) // can't use .map because foodTagList isn't an array
console.log(foodList); //prints the list of foods in array form

最后,如果你有字符串形式的 XML 并且你想进行 DOM 遍历,你可以通过DOMParser 的parseFromString方法运行它,然后使用上面的 DOM 遍历指令。


推荐阅读