tags:

views:

196

answers:

1

Suppose I have the following XML structure:

<root>
 <item>
  <item1>some text is <b>here</b></item1>
  <item2>more text is here</item2>
 </item>
</root>

I can parse the xml using something like:

$(responseXML).find('item').each(function(){
             var first_text = $(this).find('item1').text();
             var second_text = $(this).find('item2').text();
}

But the html is not preserved when using .text(). html() is not available for xml in jquery.

Any ideas on how to keep the inner html when parsing the xml?

+1  A: 

nest the sections you don't want interpreted as xml within CDATA sections e.g.

<root>
 <item>
  <item1><![CDATA[some text is <b>here</b>]]></item1>
  <item2><![CDATA[more text is here]]></item2>
 </item>
</root>

EDIT: Note, if using .text() doesn't work, try the following:

Quoting from: http://dev.jquery.com/ticket/2425

I've just re-encountered this. For the curious my workaround is instead of using .text() to use this plugin I created (simply replace .text() with .getCDATA():

jQuery.fn.getCDATA = function() {
if($.browser.msie)
    return this[0].childNodes[0].nodeValue;
    // Other browsers do this
return this[0].childNodes[1].nodeValue;
 };

It ain't pretty, but in my case did the job.

Jonathan Fingland
So if the html is not enclosed in CDATA, there is no way around it right?
safoo
correct. unless you want to try parsing the text which would get very messy, and I would advise against if you can avoid it
Jonathan Fingland