asax
asax

Reputation: 237

Parsing XML into HTML/JS

I am working on a XML to HTML conversion and I am not able to convert it into HTML. What I want is to read the xml file and then using each element and attribute, I want to display in HTML table view. But this is my attempt and it has not worked.

Here are my code.

HTML

<!DOCTYPE html>

<html>
<body>

<p id="demo"></p>

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        myFunction(xhttp);
    }
};
xhttp.open("GET", "datafile.xml", true);
xhttp.send();

function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName("location")[2];
    var txt = x.getAttribute("desc");
    document.getElementById("demo").innerHTML = txt; 
}
</script>

</body>
</html>

XML file - datafile.xml

<resultSet xmlns="urn:trimet:arrivals" queryTime="1460524583363">
    <location desc="Country Club & Wembley Park" dir="Westbound" lat="45.423844983607" lng="-122.697651868185" locid="1233"/>

    <arrival block="7867" departed="false" dir="1" status="estimated" estimated="1460528004000" fullSign="78 Beaverton TC" piece="1" route="78" scheduled="1460528004000" shortSign="78 To Beaverton TC" locid="1233" detour="false">
        <blockPosition feet="74966" at="1460524562000" heading="175" lat="45.4768926" lng="-122.8055493">
            <trip desc="Lake Oswego Transit Center" dir="0" route="78" tripNum="6322277" destDist="72719" pattern="10" progress="6417"/>
            <trip desc="Beaverton TC 78 Bay" dir="1" route="78" tripNum="6322387" destDist="8664" pattern="6" progress="0"/>
        </blockPosition>
    </arrival>

    <arrival block="7868" departed="false" dir="1" status="scheduled" fullSign="78 Beaverton TC" piece="1" route="78" scheduled="1460552534000" shortSign="78 To Beaverton TC" locid="1233" detour="false"/>

    <arrival block="3767" departed="false" dir="0" status="scheduled" fullSign="37 Lake Grove to Tualatin Park & Ride" piece="1" route="37" scheduled="1460557107000" shortSign="37 To Tualatin P&R" locid="1233" detour="false"/>

</resultSet>

Please provide some suggesting where did I go wrong and how this could be fixed.

Upvotes: 1

Views: 126

Answers (1)

user6186801
user6186801

Reputation:

Try this statement

var x = xmlDoc.getElementsByTagName("location")[0]

Upvotes: 1

Related Questions