How to parse namespace XML in Chrome 24 and jQuery

2019-07-20 08:58发布

I am trying to parse the following XML:

<catalog>
   <ns:book>
       <author>Author</author>
   </ns:book>
</catalog>

I have researched extensively and found the following (past) solutions and none of them currently work in Chrome 24 with jQuery 1.8

  $(xml).find("ns\\:book").each(function()
  {
    $("#output").append($(this).find("author").text() + "<br />");
  });

nor

  $(xml).find("book").each(function()
  {
    $("#output").append($(this).find("author").text() + "<br />");
  });

nor

  $(xml).find("[nodeName=ns:book]").each(function()
  {
    $("#output").append($(this).find("author").text() + "<br />");
  });

In my research, it would seem that this is primarily a chrome issue and not a jQuery issue. Is there an accepted solution? Is there a better js library to use for XML parsing?

1条回答
时光不老,我们不散
2楼-- · 2019-07-20 09:25

I just hit the same issue today. With jQuery 1.8.3 and Chrome 23 I've noticed 2 cases:

//Data is a string representing XML
var data = "<catalog><ns:book><author>Author</author></ns:book></catalog>";

Case 1

//Case 1
var xml = $.parseXML(data); 
//xml is a XmlDocument
$(xml).find("book");
//$(xml) is a Document
//works directly, can't seem to be able to use namespace.

Case 2.

var xml = $(data);
//xml is an Object
$(xml).find('ns\\:book')
//works just fine
查看更多
登录 后发表回答