将XML标签加载到JavaScript数组中

时间:2020-08-23 11:42:25

标签: javascript xml

我有一个JavaScript测验,我试图使用xml文件从外部加载。有24个问题。我想将问题加载到“ myQuestions”数组中,并将每个答案加载到a,b,c和d数组中。 xml文件名为MYFile.xml。非常感谢您的帮助。请,谢谢。

<question>
<text><![CDATA[<b>Question 1 Text</b>]]> </text>
<answers>
<text correct="1">1Answer 1 Text</text>
<text correct="0">1Answer 2 Text</text>
<text correct="0">1Answer 3 Text</text>
<text correct="0">1Answer 4 Text</text>
</answers>
</question>
<question>
<text><![CDATA[<b>Question 2 Text</b>]]> </text>
<answers>
<text correct="1">2Answer 1 Text</text>
<text correct="0">2Answer 2 Text</text>
<text correct="0">2Answer 3 Text</text>
<text correct="0">2Answer 4 Text</text>
</answers>
</question>

1 个答案:

答案 0 :(得分:1)

使用txml(JavaScript中最快的xml解析器)怎么样?

var xml = require("txml");
const fs = require('fs');

const data = fs.readFileSync('MYFile.xml').toString();
const dom = xml(data);
console.log(JSON.stringify(
  xml.simplifyLostLess(dom), undefined, '  '
));

这将打印:

{
  "question": [
    {
      "text": "<b>Question 1 Text</b>",
      "answers": {
        "text": [
          {
            "_attributes": {
              "correct": "1"
            },
            "value": "1Answer 1 Text"
          },
          {
            "_attributes": {
              "correct": "0"
            },
            "value": "1Answer 2 Text"
          },
          {
            "_attributes": {
              "correct": "0"
            },
            "value": "1Answer 3 Text"
          },
          {
            "_attributes": {
              "correct": "0"
            },
            "value": "1Answer 4 Text"
          }
        ]
      }
    },
    {
      "text": "<b>Question 2 Text</b>",
      "answers": {
        "text": [
          {
            "_attributes": {
              "correct": "1"
            },
            "value": "2Answer 1 Text"
          },
          {
            "_attributes": {
              "correct": "0"
            },
            "value": "2Answer 2 Text"
          },
          {
            "_attributes": {
              "correct": "0"
            },
            "value": "2Answer 3 Text"
          },
          {
            "_attributes": {
              "correct": "0"
            },
            "value": "2Answer 4 Text"
          }
        ]
      }
    }
  ]
}