jQuery最吸引我的,莫過於它強大的Selector功能了。

今天試玩了jQuery的XML查詢,發現先前用在HTML元素查詢上的Selector語法,在XML上也適用! 換句話說,不必另外記憶XMLDocument的操作指令及XPATH,直接把查HTML元素的概念搬過來也可以輕鬆搞定,真是一大福音。

就用個簡單的例子說明一切吧! 一切盡在不言中...

    var x = $(
        "<xml><products><product id=\"P1\">AA</product>" +
        "<product id=\"P2\">BB</product>" +
        "<product id=\"P3\">CC<part>X</part></product></products></xml>");
    alert(x.find("products product").size());
    alert(x.find("product:eq(1)").attr("id"));
    alert(x.find("product").eq(2).find("part").text());
    alert(x.find("product[@id='P1']").text());

PS: 在jQuery裡,如果要直接將字串轉成XML物件,記得前後方要加上<xml>及</xml>,才會被當成XML處理;XMLDocument物件則可以直接用$(xmlDoc)。

[2011-07-13更新] jQuery 1.5+增加了$.parseXML(),故寫法建議調為$($.parseXML("<products><product>....</products>")); (不用加<xml></xml>),另外product[@id='P1']的"@"符號在jQuery 1.3+後請省略。


Comments

# by Ammon

認真google了一下,看有沒有除了<xml>比較正常的做法 結果找到下面這篇 http://groups.google.com/group/jquery-en/browse_frm/thread/95718c9aab2c7483/af37adcb54b816c3?lnk=gst&q=parsexml#af37adcb54b816c3

# by 猫爸

既然是write less , do more ,用parser是不是又走 write complex了?

# by kuo

thanks for the information!

Post a comment