【发布时间】:2016-08-05 05:09:31
【问题描述】:
我正在处理 XML 到 HTML 的转换,但我无法将其转换为 HTML。我想要的是读取 xml 文件,然后使用每个元素和属性,我想在 HTML 表格视图中显示。但这是我的尝试,但没有奏效。
这是我的代码。
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 字面上包含Country Club & Wembley Park,则它无效 - stackoverflow.com/questions/730133/invalid-characters-in-xml -
这是一个方便的链接:code.tutsplus.com/tutorials/…
标签: javascript html xml dom xmlhttprequest