Parsing XML with CDATA with JQuery

僤鯓⒐⒋嵵緔 提交于 2019-11-27 23:15:00

It would seem that the XML parsing that's native to JQuery

There is no XML parsing native to jQuery. It just uses the standard XMLHttpRequest.responseXML property to get an XML DOM for the response.

discards the contents of CDATA elements

What Content-Type are you sending the response with? Because I suspect it's not being parsed as XML at all. In this case jQuery will be passing you back a string of the document, instead of an XML DOM.

Then when you call “$(xml)”, it will be creating document content from that string(*) — parsed as HTML, not XML. In HTML there is no such thing as a CDATA section, so browsers might discard them, or treat them as comments.

I suspect this because “project.html()” shouldn't actually work when the document is XML. ‘html()’ just returns the same as the standard ‘innerHTML’ property(**), which only works for HTML documents; it is undefined on XML elements.

Enclosing the output in CDATA tags allows us to rest relatively assured that we're sending back valid data via our API.

Well, ‘relatively’: if your data happens to contain “]]>” you still lose. <![CDATA[ sections are intended as a crutch to improve writability for hand authoring; machine-generated XML should really just use entity-encoding in the normal fashion. Usually the server app should be using proper XML tools to generate the response in which case this will be done automatically.

(*: I have never understood when jQuery feels the need to squish document fragment creation and CSS selection into the same function. They're completely different operations which you don't want to get confused, as may have happened here.)

(**: Actually, it tries to filter out jQuery custom attributes first, using a regex. Unfortunately since regex cannot parse HTML, it will happily filter out valid parts of your text that happen to look like HTML attributes. Whoops. Not one of jQuery's prettier parts.)

jquery does in fact have an xml parser now that should solve your problem. $.parseXML(xml) http://api.jquery.com/jQuery.parseXML/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!