我有一个 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/