2016-08-19 218 views
0

我期待解析這個.xml文件如何解析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

我有我想解析並放入HTML的xml。我必須在我的HTML中創建一個貫穿XML樹的函數,但我不知道如何創建可以提取頁面列表中所有屬性(如'id')的函數。 – george1912

回答

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'));
<div id="result"></div>

顯然不是解析XML的字符串的DOMParser的你想使用一個XMLHttpRequest的responseXML的,但一旦你有,你可以如圖所示讀出一個元素的屬性。