繁体   English   中英

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

[英]Retrieving only the names from an xml file and putting them into an array in 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);
}

有两种方法可以解决此问题。 如果您有需要运行的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遍历说明。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM