jQuery从XML中剥离标签

时间:2011-12-17 07:05:05

标签: javascript xml jquery

我有一个页面,它充当使用jQuery的AJAX加载器。它会像这样获取XML文档,并将titleauthPhrasecontent的值插入到显示页面中的相应div中。

<?xml version="1.0" encoding="utf-8"?>
<tinglePage>
  <title>Home</title>
  <authPhrase>welcome, Jashank<br /><a href="/tingle/auth/logout">logout</a></authPhrase>
  <content>
    <p>There are <strong>two</strong> types of folks who sit around
    thinking about how to kill people: <em>psychopaths</em> and
    <em>mystery writers</em>.  I'm the kind who pays better.</p>
  </content>
</tinglePage>

当我使用此JavaScript时,它会从插入的内容中删除标记。

    jQuery.get(path, {ajax: "true"}, function(xml) {
        document.title = "Tingle :: " + $("title", xml).text();
        $(".pageTitle").html(
            $("title", xml).text()
        );

        $(".authPhrase").html(
            $("authPhrase", xml).text()
        );

        $(".content").html(
            $("content", xml).text()
        );
    });

有没有办法将XML插入显示的页面而不剥离内容?

2 个答案:

答案 0 :(得分:2)

您应该使用CDATA块包装内容。这样,当您使用.text()时,您将获得包含html标记的全部内容;

<?xml version="1.0" encoding="utf-8"?>
<tinglePage>
  <title>Home</title>
  <authPhrase><![CDATA[welcome, Jashank<br /><a href="/tingle/auth/logout">logout</a>]]></authPhrase>
  <content>
    <![CDATA[<p>There are <strong>two</strong> types of folks who sit around
    thinking about how to kill people: <em>psychopaths</em> and
    <em>mystery writers</em>.  I'm the kind who pays better.</p>]]>
  </content>
</tinglePage>

Working example

答案 1 :(得分:0)

.text()方法仅返回html标记之间的字符(保留空格和html实体)。 .html()方法返回字符而不进行任何额外处理;如果我的记忆正确地为我服务:)

相关问题