---
title: "通过JavaScript 来解析 XML"
author: "JavaScanner"
date: "2010-10-27T11:29:18Z"
tags: ["Firefox", "IE", "JavaScript", "Opera", "XML"]
categories: ["Web前端"]
slug: "javascript-xml"
draft: false
lastmod: "2010-10-27T11:29:18Z"
id: 795343
url: "https://javascanner.iteye.com/blog/795343"
---

在网上找到一个通过js解析xml的例子，觉得不错，就转了过来可以参考看看

 

 

   **一个简单的xml文件**：

 

```
  <?xml version="1.0" encoding="ISO-8859-1" ?> 
- <!--   Copyright w3school.com.cn 
  --> 
- <note>
  <to>George</to> 
  <from>John</from> 
  <heading>Reminder</heading> 
  <body>Don't forget the meeting!</body> 
  </note>
```

 

**加载并解析xml文件**：

 

 

```
<html>
<head>
<script type="text/javascript">
function parseXML()
{
try //Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  }
catch(e)
  {
  try //Firefox, Mozilla, Opera, etc.
    {
    xmlDoc=document.implementation.createDocument("","",null);
    }
  catch(e)
    {
    alert(e.message);
    return;
    }
  }
xmlDoc.async=false;
xmlDoc.load("/example/xmle/note.xml");
document.getElementById("to").innerHTML=xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("heading").innerHTML=xmlDoc.getElementsByTagName("heading")[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;
}
</script>
</head>

<body onload="parseXML()">
<h1>javascript解析xml</h1>
<p><b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>heading:</b> <span id="heading"></span><br />
<b>Message:</b> <span id="message"></span>
</p>
</body>
</html>
```

 

**运行结果为**：

 

 

To: George  
From: John  
heading: Reminder  
Message: Don't forget the meeting!

 

 

**遍历xml节点数：**

 

   

```
<html>
<body>
<script type="text/javascript">
var xmlDoc;
// code for IE
if (window.ActiveXObject)
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation.createDocument)
{
xmlDoc=document.implementation.createDocument("","",null);
}
else
{
alert('Your browser cannot handle this script');
}
xmlDoc.async=false;
xmlDoc.load("/example/xmle/note.xml");

var x=xmlDoc.documentElement.childNodes;

for (var i=0;i<x.length;i++)
{ 
if (x[i].nodeType==1)
  { 
  //Process only element (nodeType 1) nodes
  document.write(x[i].nodeName + ": ");
  document.write(x[i].childNodes[0].nodeValue);
  document.write("<br />");
  } 
}
</script>
</body>
</html>
```

 

**运行结果为：**

to: George  
from: John  
heading: Reminder  
body: Don't forget the meeting!