0
var xml = '<books><book><id>1</id></book></books>';
var xmlDoc = $.parseXML(xml);
$(xmlDoc).find("book").each(function(){
  alert($(this));
});

What i want to see is:

<book><id>1</id></book>

In IE, i can use $(this)[0].xml. But in Chrome, there's no xml property. What should I do then?

Thanks.

Nico
  • 409
  • 3
  • 13

2 Answers2

3

The easiest way is to use the browser's built-in XMLSerializer implementation (present in the current versions of all major browsers, including IE 9):

function serializeXmlNode(xmlNode) {
    if (typeof window.XMLSerializer != "undefined") {
        return new window.XMLSerializer().serializeToString(xmlNode);
    } else if (typeof xmlNode.xml != "undefined") {
        return xmlNode.xml;
    }
    return "";
}

var xml = '<books><book><id>1</id></book></books>';
var xmlDoc = $.parseXML(xml);
$(xmlDoc).find("book").each(function(){
    alert( serializeXmlNode(this) );
});

References:

Tim Down
  • 306,503
  • 71
  • 443
  • 520
0

If you want to see 1 (the text of the id element within the book element), use

alert($(this).find('id').text());

Live Example | Source

(Your formatting completely changes the question -- the importance of formatting correctly in the first place!)

Update:

I believe the only way to get this (other than writing your own DOM-to-XML serializer) (no, there's another, probably better way) is to wrap it in another element and use html:

alert($("<x>").append(this).html()); // <== Probably dangerous

...but that will move the element out of the original document. So you can avoid that by cloning:

alert($("<x>").append(this.cloneNode(true)).html());

Live Example | Source

Community
  • 1
  • 1
T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
  • Modern browsers implement `XMLSerializer`, which does the job properly. – Tim Down Nov 02 '12 at 10:50
  • Thanks T.J. I didn't expect you would reply in such a short notice. I realized the formatting error right after the question was posted and corrected at once. – Nico Nov 03 '12 at 02:21