2011-08-18 59 views
0

任何人都知道如何使用Jquery瀏覽XML文件,並且只從其中包含文本值的標籤打印標籤名稱和文本值?如何使用Jquery從XML文件打印每個值?

例如HTML輸出,如:

id: 00130000004EQCpAAO 
updated: 2011-08-16 19:40:51 
account_type: Vendor Other 
active: 1 
someprop_d: 0 

是來自於XML,如:

<accounts> 
    <id>00130000004EQCpAAO</id> 
    <updated>2011-08-16 19:40:51</updated> 
    <account_type>Vendor Other</account_type> 
    <someprop_a/> 
    <active_c>1</active_c> 
    <someprob_b/> 
    <someprop_c/> 
    <someprop_d>0</someprop_d> 
</accounts> 

jQuery的:

var mystr = $.ajax({ 
    type: 'GET', 
    url: '/js/data_account.xml', 
    async: false, 
    data: { 
     key: "value" 
    }, 
    dataType: "xml", 
    success: function(data) { 
     var xml = $(data) 
     //var $accountid = xml.find("id").text(); 
     // do something relevant here 
     //return something; 
    }, 
    error: function() { 
     alert("error: call failed"); 
    } 
}); 
$('parentElement').append(mystr); 

回答

4

你可以看看.nodeName屬性的值來獲得標籤名稱並使用.text()獲取文本內容。例如:

var idNode = xml.find("id"); 
var nodeName = idNode[0].nodeName; 
var nodeText = idNode.text(); 

可以遍歷XML並得到輸出你想要的:

xml.find("accounts > *").each(function() { 
    var text = $(this).text(); 
    if (text) { 
     $("#xmlOutput").append($("<div>").text(this.nodeName + ": " + text)); 
    } 
}); 

工作演示:http://jsfiddle.net/gilly3/KYWCK/

0
$(xml).find('accounts').each(function(){ 
    var $accountid = $(this).find('id').text(); 
    alert($accountid); 
});