1
我正在處理XML到HTML的轉換,但我無法將其轉換爲HTML。我想要的是讀取XML文件,然後使用每個元素和屬性,我想在HTML表格視圖中顯示。但這是我的嘗試,並沒有奏效。將XML解析爲HTML/JS
這是我的代碼。
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文件 - 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>
請提供一些建議沒我有什麼錯,如何這可能是固定的。
您的XML只有一個'location'節點,但您要訪問與'[2]',不存在第三個節點。此外,如果你的XML字面上包含「鄉村俱樂部和溫布利公園」,這是無效的 - http://stackoverflow.com/questions/730133/invalid-characters-in-xml –
這裏有一個方便的鏈接:http://代碼。 tutsplus.com/tutorials/quick-tip-use-jquery-to-retrieve-data-from-an-xml-file--net-390 –