2 回答
TA贡献1895条经验 获得超7个赞
$(function(){
var data = '<?xml version="1.0" encoding="UTF-8"?><flightInfo><Date>02OCT19</Date><Flight> VA 1429 </Flight><Depart>Sydney</Depart><Arrive>Cairns</Arrive><Boarding>Gate 35 At 1855</Boarding><Carrier>Virgin Australia</Carrier></flightInfo>'
//Parse the givn XML
var xmlDoc1 = $.parseXML( data );
var $xml1 = $(xmlDoc1);
// Find Person Tag
var $flightInfo = $xml1.find("flightInfo");
$flightInfo.each(function(){
var Date = $(this).find('Date').text(),
Depart = $(this).find('Depart').text(),
Arrive = $(this).find('Arrive').text() ;
$("#data" ).append('<li>' + Date + ' - ' + Depart+ ' - ' + Arrive + '</li>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="data"></ul>
首先,您需要在 xml 对象中解析您的数据,如下所示,然后您可以读取它。尝试以下解决方案。
<ul id="data"></ul>
<script>
$(function(){
var data = '<?xml version="1.0" encoding="UTF-8"?><flightInfo><Date>02OCT19</Date><Flight> VA 1429 </Flight><Depart>Sydney</Depart><Arrive>Cairns</Arrive><Boarding>Gate 35 At 1855</Boarding><Carrier>Virgin Australia</Carrier></flightInfo>'
//Parse the givn XML
var xmlDoc1 = $.parseXML( data );
var $xml1 = $(xmlDoc1);
// Find Person Tag
var $flightInfo = $xml1.find("flightInfo");
$flightInfo.each(function(){
var Date = $(this).find('Date').text(),
Depart = $(this).find('Depart').text(),
Arrive = $(this).find('Arrive').text() ;
$("#data" ).append('<li>' + Date + ' - ' + Depart+ ' - ' + Arrive + '</li>');
});
});
</script>
检查现场演示:
http://jsfiddle.net/ru92p4en/
TA贡献1780条经验 获得超4个赞
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<button type="button" onclick="loadDoc()">Get flight
information</button>
<br><br>
<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "Question1.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table=`<tr><th>Depart</th><th>Arrive</th></tr>`;
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += `<tr><td>` +
x[i].getElementsByTagName("Depart")[0].childNodes[0].nodeValue +
`</td><td>` +
x[i].getElementsByTagName("Arrive")[0].childNodes[0].nodeValue +
`</td><td>` +
x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue +
`</td></tr>`;
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
我认为这应该有所帮助。
添加回答
举报