Reading an XML file into an array

I have used a JS quiz script from https://www.sitepoint.com/simple-javascript-quiz/ However, I should like to remove the quiz questions and answers from the JS and put them into an XML file, but I am falling at the first hurdle - how to read an XML file into an array. :unhappy: Can some kind soul point me in the right direction, please?

Is there a reason in particular for XML over JSON?

There’s the old DOMParser which would work.

1 Like

Only that I didn’t think of it! :blush: I just figured it didn’t really belong in the JS. I guess JSON would be easier…

I mean, if you’re writing the file…

var data = {JSONstructuregoes here}

and then

<script src="questions.json">

Loads your array for you.
(strictly speaking this is then just an external .js file, you could create a pure JSON file and then ajax it in as data. Little more complex that way though.)

1 Like

If you’re fetching the data with AJAX you can actually directly get the XMLHttpRequest.responseXML and query it like the document:

const xhr = new XMLHttpRequest()

xhr.open('GET', './data.xml')

xhr.addEventListener('load', () => {
  const data = xhr.responseXML
  const questions = data.querySelectorAll('question')

  console.log(questions)
})

xhr.send()

But yeah as @m_hutley said, JSON would probably be easier to handle…

3 Likes

Before I go completely doo-lally-tat, I’m struggling to get my JSON file right. I currently have

var data = '[
    {
      question: "Malawi is in which continent?",
      answers: {
        a: "Africa",
        b: "Asia",
        c: "North America"
      },
      correctAnswer: "a"
    },
    {
      question: ...
    }
]';

but I’m getting a console error SyntaxError: '' string literal contains an unescaped line break which I understand, but I’m not sure how to fix!

You either have to concatenate the lines with +, use a template literal instead (which is nicer but unfortunately won’t work in IE), or, well, write it all in one line.

But if you directly assign it to a variable anyway, there’s actually no need to write it as a JSON string in the first place:

var data = [
  {
    question: '...',
    answers: { /* ... */ }
  }
]

Edit: OK… at which point we are pretty much where we began. :-P So if you want to put the data in an actual JSON file, you can’t assign its contents to a variable like this; you have to load it with AJAX. With JSON it works similar to the above snippet:

const xhr = new XMLHttpRequest()

xhr.open('GET', './data.json')

xhr.addEventListener('load', () => {
  const questions = JSON.parse(xhr.responseText)

  console.log(questions)
})

xhr.send()
1 Like

Haha. So we are, except it has separated the quiz engine from the Qs and As, so I can use 1 quiz engine with multiple sets of questions and answers. (I think…)

1 Like

True! :-)

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.