仅从xml文件中检索名称,并将其放入JavaScript中的数组

时间:2019-07-11 22:37:42

标签: javascript arrays xml split

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

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

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

//过去,我编写了这段代码来从带有分数列表的文件中检索分数(从注释中打开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);
}

1 个答案:

答案 0 :(得分:0)

有两种方法可以解决此问题。如果您有一个需要运行的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's parseFromString method运行它,然后使用上面的DOM遍历说明。