1

我一直在寻找一个类似的问题以避免提出已经解决的问题,但我还没有找到适合我的有效答案,抱歉,如果有,我还没有看到。我正在从 Jquery 读取一个 XML 文件,该 xml 文件有一些我特意添加的 CDATA 内容,我想保留这些内容以用于格式化目的:

<?xml version="1.0" encoding="UTF-8"?>
<categories>
    <description name="whatever">
        Blah, blah, blah<![CDATA[<br />]]>blah, blah, blah
    </description>
</categories>

阅读后,我将其附加到一个 div 中:

$(xml).find('description[name="whatever"]').each(function()
{       
    $(container).append($(this));
});

我所拥有的是 Jquery 似乎避开了 '<' 和 '>' 所以我终于有了:

Blah, blah, blah&l;tbr /&gt;blah, blah, blah

我已经尝试强制附加将内容视为文本,如下所示:

$(container).text($(this));

但后来我得到:

[Object object]

如果我这样做 .html() 我会得到与 .append() 相同的结果...

4

2 回答 2

2

Ordinary XML processors have no way of knowing whether anything they process came from a CDATA section; as far as they know, any CDATA content is just plain text. As such, when jQuery processes CDATA stuff, it isn't going to treat it any differently than stuff that appeared in a string literal (in fact, since jQuery is simply a layer over the DOM, it has absolutely no way of knowing whether its input came from a CDATA section or a string literal, since the DOM doesn't make any such distinction).

于 2013-02-28T10:22:58.190 回答
1

For the folks that may fall in the same hole in the future:

First of all, declare it as XML:

$.get("yourxml.xml", {}, function (data) 
{            

},'xml');

Afterwards, introduce it like text:

$(xml).find('description[name="whatever"]').each(function()
{       
    $(container).append($(this).text());
});

This is working for me like a charm!

于 2013-02-28T16:41:41.983 回答