【问题标题】:jquery parse html in xmljquery在xml中解析html
【发布时间】:2011-06-08 10:02:47
【问题描述】:

我有一个 xml 文件,其中包含我使用 jquery ajax 解析的 html 标签。 我可以毫无问题地获取文本值。如何获取元素中的 html 部分?

编辑:我尝试将 html 包装在 cdata 中,但希望将 xhtml 包含在 xml 中。

$.ajax({ type: "GET",
                        url: "product.xml",
                        dataType: "xml",
                        success: function (xml) {

                            $(xml).find("product[productid=" + selection + "]").each(function () {
                                var $title = $(this).find("title").text();        //get title  
                                var $desc = $(this).find("description").html();          //get description  
                                //$('[nodeName=]',xml)
                                $("#producttitle").html("");
                                $("#productdesc").append($desc);
                                $("#producttitle").append($title);

                            });

                        }  

<product productid="1">
    <title>Active Directory</title>
    <status>noinfo</status>
    <description>
        Headline
        <b>tester</b>
        <ul>
            <li>test list element</li>
        </ul>
    </description>
    <link title=""></link>
</product>

干杯, 特里

【问题讨论】:

  • 嗯基本上是通常的 jquery.ajax $.ajax({ type: "GET", url: "product.xml", dataType: "xml", success: function (xml) {... . 我用 var $desc = $(this).find("description").text(); 得到值;

标签: jquery xml html-parsing


【解决方案1】:

要获取包含标签而不是转义为文本内容的内容,请使用html:

var $desc = $(this).find("description").html();

但是,如果您将此内容插入到文档中,则不需要获取 HTML —— 您只需附加选择即可:

$(this).find('description').clone().appendTo('#containingElement');

clone 是导入节点所必需的。

【讨论】:

  • 不幸的是,使用 .html() 不适用于 ajax 数据类型 xml。
  • @Terry 谢谢,我已经删除了那个位。
【解决方案2】:

尝试将xml文件读取为html:

$.ajax({ 类型:“获取”, 网址:'file.xml', 数据类型:“html”, 成功:函数(xml){ ....

【讨论】:

  • 使用“HTML”数据类型(而不是“XML”)帮助解决了由于 XML 中包含不受支持的特殊字符编码而导致 JQuery XML 解析器失败的问题。
【解决方案3】:

仅使用 $(this).find("description").html() 似乎有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多