jQuery使用命名空间解析XML

时间:2015-06-23 02:38:57

标签: 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()正常工作。

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

非常感谢。

1 个答案:

答案 0 :(得分:1)

我找到的一种hacky方式是使用2个选择器

  for x in range(1, 5):
    m = myModel()
    m.articleId = "some constant"
    m.save()

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);

相关问题