js獲取並解析xml檔案程式碼例項

antzone發表於2017-04-11

雖說現在的javascript越來越多的和json格式資料配合使用。

但是xml檔案的使用也是非常的頻繁,下面就分享一段程式碼例項,它實現了使用javascript獲取並解析xml檔案的功能。

一.xml檔案程式碼:

[XML] 純文字檢視 複製程式碼
<?xml version="1.0" encoding="ISO-8859-1" ?> 
<note>
  <to>duncan</to> 
  <from>John</from> 
  <heading>Reminder</heading> 
  <body>Don't forget the meeting!</body> 
</note>

二.解析程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
function parseXML(){
  //Internet Explorer
  try{
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  }
  catch(e){
    //Firefox, Mozilla, Opera, etc.
    try {
      xmlDoc=document.implementation.createDocument("","",null);
    }
    catch(e){
      alert(e.message);
      return;
    }
  }
  xmlDoc.async=false;
  xmlDoc.load("note.xml");
  document.getElementById("to").innerHTML=xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
  document.getElementById("from").innerHTML=xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
  document.getElementById("message").innerHTML=xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
window.onload = function () {
  parseXML()
}
</script>
</head>
<body>
<h1><a href="http://www.nowamagic.net" target="_blank">www.nowamagic.net</a></h1>
<p>
  <b>To:</b> <span id="to"></span><br />
  <b>From:</b> <span id="from"></span><br />
  <b>Message:</b> <span id="message"></span>
</p>
</body>
</html>

xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue 這段程式碼如何理解:

(1).xmlDoc -由解析器建立的 XML 文件。

(2).getElementsByTagName("to")[0] - 第一個 <to> 元素。

(3).childNodes[0] - <to> 元素的第一個子元素(文字節點)。

(4).nodeValue - 節點的值(文字本身)。

如果xml檔案為:

[XML] 純文字檢視 複製程式碼
<?xml version="1.0" encoding="ISO-8859-1" ?> 
<note>
  <to>antzone
    <too>duncan1</too>    
  </to> 
   <too>duncan2</too>
   <from>John</from> 
   <heading>Reminder</heading> 
   <body>Don't forget the meeting!</body> 
</note>

讀取第一個<too>:xmlDoc.getElementsByTagName("to")[0].getElementsByTagName("t00")[0].childNodes[0].nodeValue。

讀取第二個<too>:xmlDoc.getElementsByTagName("too")[0].childNodes[0].nodeValue。

相關文章