kexxcream
kexxcream

Reputation: 5933

Outputting XML data to HTML by use of JS

Problem:

Trying to print one question and 4 answers at a time from an XML file.

JS code:

var xmlDoc, quest, ans, i, n;

xmlDoc = loadXMLDoc("questions.xml");
quest = xmlDoc.getElementsByTagName('main');

document.write("<table border='1'>");

for (i = 0; i < quest.length; i+=1)
{
    document.write("<tr><td>");
    document.write( quest[i].childNodes[0].nodeValue );
    document.write("</td></tr>");

    for(n = 0; n < 4; n++) 
    {
        document.write("<tr><td>");
        document.write( quest[i].childNodes[n].nodeValue );
        document.write("</td></tr>");
    }
}

document.write("</table>");

Desired output:

Each question comes with four answers below it. Right now only the questions are being printed correctly.

The structure for the XML file is:

<main>
    <instruction></instruction>
    <solution></solution>
    <solution></solution>
    <solution></solution>
    <solution></solution>
</main>

Upvotes: 0

Views: 73

Answers (1)

mehulmpt
mehulmpt

Reputation: 16577

It should be something like this:

var xmlDoc, quest, ans, i, n;

xmlDoc = loadXMLDoc("questions.xml");
quest = xmlDoc.getElementsByTagName('main');

document.write("<table border='1'>");

for (i = 0; i < quest.length; i+=1)
{
    document.write("<tr><td>");
    document.write( quest[i].childNodes[0].nodeValue );
    document.write("</td></tr>");

    for(n = 1; n < 5; n++) // m = 1 because [0] is the title.
    {
        document.write("<tr><td>");
        document.write( quest[i].childNodes[n].nodeValue );
        document.write("</td></tr>");
    }
}

document.write("</table>");

Upvotes: 1

Related Questions