如何使用jQuery从XML文件中获取包括标签的全文

时间:2010-09-09 06:26:43

标签: jquery xml text tags

我有一个xml文件,如:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<legends>
<legend>
<number>1</number>
<legendString><ul><li>1.across:a system of rules of conduct or method of practice</li><li>1.down:a disagreement or argument about something important</li><li>2.down:any broad thin surface</li><li>3.across:the passage of  pedestrians or vehicles </li></ul></legendString>
</legend>
......
<legends>

如何使用jQuery获取包括标签在内的全文。 字符串

<ul><li>1.across:a system of rules of conduct or method of practice</li><li>1.down:a disagreement or argument about something important</li><li>2.down:any broad thin surface</li><li>3.across:the passage of  pedestrians or vehicles </li></ul>
如果我进行函数调用,应该传递

。 如果我打电话:

var legendStr = $(this).find("legendString").text();
legendStr中不会出现

标签。

我该怎样继续。

这是jQuery脚本:

var randomnumber=Math.floor(Math.random()*233);
    $.get("legends.xml",{},function(xml){  



       $(xml).find("legend").each(function(){   


                if(randomnumber == $(this).find("number").text())
                {
              var c = "legendString";

              var legendStr = $(this).find(c).html();         


              $("#sidebar > ul").html(legendStr);
                }



       });
       },"xml");

3 个答案:

答案 0 :(得分:1)

你想要的     $(本).find( “legendString”)。HTML()

我仔细研究了jQuery对XML的支持。 .html()不支持XML文档。因此,您需要使用traversing methods和/或XML DOM

所以,例如,您可以进行深度优先遍历,直到找到文本节点(即nodeType == 3),然后您可以使用nodeName(例如<ul> )和.text()获取标签名称和文本。

答案 1 :(得分:0)

尝试使用.html()方法保留代码:

var legendStr = $(this).find('legendString').html();

另请注意,.find('legendString')会查找名为legendString的标记,这可能不是您要查找的标记。您可能需要:contains()选择器。

答案 2 :(得分:0)

我认为你需要的功能不是jQuery开箱即用的功能。但你可以写自己的。以下是您的出发点:

jQuery.extend(jQuery.fn, {
outerHtml: function(tagName) {
    var matches = this.find(tagName);
    var result = '';
    for (var i=0; i<matches.length; i++) {
        var el = matches[i];
        result += '<' + tagName;

        for (var i=0; i<el.attributes.length; i++) {
            result += ' ';
            result += el.attributes[i].name;
            result += "='";
            result += el.attributes[i].value;
            result += "'";
        }
        if (el.innerHTML == null) { result += '/>'; }
        else { 
        result += '>';
        result += el.innerHTML;
        result += '</'
        result += tagName;
        result += '>';
    }
    return result;
}

}});

因此,你将能够做到

var legendString = $(this).outerHtml('legendString');