---
title: "ie无法使用jquery解析xml（转）"
author: "传说中的旅人"
date: "2011-07-07T15:40:49Z"
tags: []
categories: ["Web前端"]
slug: "ie-jquery-xml"
draft: false
lastmod: "2011-07-07T15:40:49Z"
id: 1118874
url: "https://lengend.iteye.com/blog/1118874"
---

功能描述：使用jQuery解析已经定义好内容的xml文件

1.xml文件:menu.xml

```
<?xml version="1.0" encoding="gb2312"?>
<menus>
    <menu>
        <id>1</id>
        <name>system</name>
        <parentId>0</parentId>
        <target>mainFrame</target>
        <url></url>
    </menu>
    <menu>
        <id>2</id>
        <name>company</name>
        <parentId>1</parentId>
        <target>mainFrame</target>
        <url></url>
    </menu>
</menus>
```

 2.自定义js文件解析xml文件:index.js

```
$(document).ready(function(){
    $.ajax({
           url:"xml/menu.xml ",
           type:"POST", 
           dataType:"xml",
           success:function(data){
                      $(data).find("menu").each(function(){
                               alert("success");
                               alert($(this).text());
                      });
           },
           error:function(data){
                     alert("fail:");
           }
    });
});
```

 3.新建index.html文件引入jQuery.js、xml文件及index.js文件，在ie中（任何版本）运行index.html，结果总是弹出“fail”，但是在Firefox中的结果却是“success”。

在网上搜了很多资料，最后在这篇文章[http://www.newmediafun.com/2009/07/parsing-xml-with-jquery-in-internet-explorer/](http://www.newmediafun.com/2009/07/parsing-xml-with-jquery-in-internet-explorer/)上找到了解决方案。是因为ie中的限制无法正确解析xml文件，它解析出的是一个text对象(在我引用的文章中有更详细的解释)所以针对这个加入判断就可以解决了

正确代码index.js

```
$(document).ready(function(){
    $.ajax({
         url:"xml/menu.xml",
         type:"POST", 
         dataType:($.browser.msie) ? "text" : "xml",
         success:function(data){
                var xml;
                if( typeof data == "string" ){
                         xml = new ActiveXObject("Microsoft.XMLDOM");
                         xml.async = false;
                         xml.loadXML(data);
                } else {
                         xml = data; 
                }
              $(xml).find("menu").each(function(){
                  alert("success");
                  alert($(this).text());
              });
        },
       error:function(data){
               alert("fail:");
       }
    });
});
```