jQuery 使用命名空间解析 XML

标签 jquery xml namespaces

我有一个 XML api 返回 XML,如下所示:

    <?xml version="1.0" encoding="utf-8"?>
    <d:ItemCount xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml" m:type="Edm.Int32">
       529
    </d:ItemCount>

我使用 jQuery 来解析这个 XML,如下所示:
    $.ajax({
    cache: false,
    type: "GET",
    url: apiURL  ,
    dataType: 'xml',
   // contentType: "application/x-www-form-urlencoded;charset=UTF-8" ,
    success: function (xml) {

           var root = $(xml);
           var count = root.find('d\\:ItemCount').text(); 
           alert(count);
    },
    error: function (xhr, ajaxOptions, thrownError) {
    }
 });

但是,使用 Chrome 时,警报结果始终为空字符串。当我尝试使用“root.find('ItemCount').text()”而不是“root.find('d\:ItemCount').text()”时,它会起作用。

使用 IE 11 时,情况完全不同。警报结果始终为空字符串,使用 root.find('ItemCount').text()并使用 root.find('d\\:ItemCount').text() 工作正常.

那么处理这个问题的最佳方法是什么?

非常感谢。

最佳答案

我发现的一种 hacky 方法是使用 2 个选择器

var root = $(xml);
var count = root.find('d\\:ItemCount, ItemCount').text();
console.log(count);

var string = '<?xml version="1.0" encoding="utf-8"?><d:ItemCount xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml" m:type="Edm.Int32">529</d:ItemCount>';

var xml = $.parseXML(string);
var root = $(xml);
var count = root.find('d\\:ItemCount, ItemCount').text();
console.log(count);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

关于jQuery 使用命名空间解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30992975/

相关文章:

iOS SDK 抓取xml代码中的元素

c# - 无效操作异常 : The type of the argument object 'Scratch' is not primitive

c++ - 如果参数与数据成员同名怎么办?

javascript - 无法在 jquery read() 中找到先前插入的元素

javascript - 如何选择多个值或在jquery中搜索和设置值

javascript - jQuery 中的旋转轮

python - 在 Python 中,如何从导入的模块访问主模块的命名空间?

javascript - 仅限 Firefox/IE - gif 动画在 element show() jquery 之后卡住

Javascript XML 相同元素名称

php - 如何为 PHP-include 提供自己的命名空间(如 Python 中的 "from a import MyClass")?