문제

I am working on a little website idea, and I am not very great at any of this. I basically have an HTML quiz that will prompt the user with questions that I defined in an XML.

window.onload = function xml() 
{
    // get form from HTML
    var form = document.getElementById("form");

    // get XML document
    if (window.XMLHttpRequest)
    {
            var xmlhttp = new XMLHttpRequest();
    }

    // open XML
    xmlhttp.open("GET", "questions.xml", false);
    xmlhttp.send(null);

    // initialize elements for do document, questions, and details
    var xmlDoc = xmlhttp.responseXML;
    var question = xmlDoc.getElementsByTagName("question");

On the line above, I get an error saying "Cannot call method 'getElementsByTagName' of null". The strange thing, however, is that I only get said error if the XML file has multiple "question" tags. If I only have one "question" tag in my XML, the whole function works perfectly. So I am wondering what is going on in this case, and why it won't work for me.

(the rest of the code below shows where I begin to go with the function)

    var qXML = xmlDoc.getElementsByTagName("q");

    // write values into HTML for each question
    for ( i = 0 ; i < question.length ; i++ )
    {
        // qBlock div for question
        var div = document.createElement('div');
        div.className = "qBlock";

This code continues for a while to get all fields in the HTML. In total, this block of code in the loop works all the way throughout, unless there are multiple "question" elements.

Thank you so much to anyone who can help / teach me on any of this. Also feel free to tell me if I am doing anything else incorrectly. I am open to any criticism.

도움이 되었습니까?

해결책

While I can't be sure this is the problem without seeing your questions.xml file, you may have multiple root elements. For example:

<?xml version="1.0"?>
<question>...</question>
<question>...</question>

XML does not allow that, and it will fail to parse. Wrap them up in one root element:

<?xml version="1.0"?>
<questions>
    <question>...</question>
    <question>...</question>
</questions>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top