简体   繁体   中英

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>

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>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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