Frank
Frank

Reputation: 569

jQuery parse XML with namespace

I have a XML api returns XML like below:

    <?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>

I use jQuery to parse this XML like below:

    $.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) {
    }
 });

However, using Chrome, the alert result is always empty string. when I tried using "root.find('ItemCount').text()" instead of "root.find('d\:ItemCount').text()", it will works.

While using IE 11, things are quite different. the alert result is always empty string using root.find('ItemCount').text() and works fine using root.find('d\\:ItemCount').text().

So what is the best way to handle this?

Many thanks.

Upvotes: 0

Views: 905

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

One hacky way I have found is to use 2 selectors

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>

Upvotes: 2

Related Questions