我希望解析这个.xml
文档
<instances>
<courseInstance id="147209" instanceCode="ENGLISH"
courseInstanceID="ENGLISH_147209" courseCode="ENGLISH"
courseDescription="ENGLISH Program" courseYear="1"
startDate="2014-06-01" session="2014" modeOfStudyCode="FULL_TIME"
modeOfStudyDescription="Full Time" courseStreamCode="A"
courseStreamDescription="Stream A" courseFee="0" waitlist="0"
waitlistPlacesLeft="0" instanceStatusCode="PROGRAM_OPEN"
instanceStatusDescription="Program Open">
<service cis="147249" serviceCode="ONLINE_REG"
serviceName="Enroll and Pay" startDate="2016-08-04"
active="1" url="https://xxxx-xxx.xxxx.com/app/xxx/f?p=PV_ONLINE_REG:101:::::APP_COURSE_INSTANCE:147209"/>
</courseInstance>
<instances>
我想在页面中显示HTML,我在列表中列出每个属性。
这是我的代码
<h2>Demo</h2>
<div id='show_LIVE_LINK'></div>
<script>
displayCourses(0);
function displayCourses(i) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp, i);
}
};
xmlhttp.open("GET", "solar.qll_web.common.xml", true);
xmlhttp.send();
}
function myFunction(xml, i) {
var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("instances");
document.getElementById("show_LIVE_LINK").innerHTML = "courseInstance: " + x[i].getElementsByTagName("courseInstance")
}
</script>
我如何一个接一个地垂直向下看属性?
答案 0 :(得分:0)
元素节点有一个attributes
集合:
var xml = `<instances>
<courseInstance id="147209" instanceCode="ENGLISH"
courseInstanceID="ENGLISH_147209" courseCode="ENGLISH"
courseDescription="ENGLISH Program" courseYear="1"
startDate="2014-06-01" session="2014" modeOfStudyCode="FULL_TIME"
modeOfStudyDescription="Full Time" courseStreamCode="A"
courseStreamDescription="Stream A" courseFee="0" waitlist="0"
waitlistPlacesLeft="0" instanceStatusCode="PROGRAM_OPEN"
instanceStatusDescription="Program Open"/>
</instances>`;
var xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
function display(xmlDoc, index, targetEl) {
targetEl.textContent = '';
var ul = document.createElement('ul');
[].forEach.call(xmlDoc.getElementsByTagName('courseInstance')[index].attributes, function(att) {
var li = document.createElement('li');
li.textContent = att.name + ' : ' + att.value;
ul.appendChild(li);
});
targetEl.appendChild(ul);
}
display(xmlDoc, 0, document.getElementById('result'));
&#13;
<div id="result"></div>
&#13;
显然,您不想使用DOMParser解析XML字符串,而是使用XMLHttpRequest的responseXML,但是一旦有了,就可以读出元素的属性,如图所示。