2011-05-12 16 views

回答

0

試試這個XPath表達式:

//span[starts-with(@id, 'startsWith_')] 
+0

嘿,沒有工作。 :^( – user647345 2011-05-12 06:52:44

1

下面是一個例子:

require 'nokogiri' 

html = ' 
<html> 
<body> 
    <span id="doesnt_start_with">foo</span> 
    <span id="startsWith_bar">bar</span> 
</body> 
</html>' 

doc = Nokogiri::HTML(html) 
p doc.search('//span[starts-with(@id, "startsWith_")]').to_xml 

這就是如何選擇它們。

doc.search('//span[starts-with(@id, "startsWith_")]').each do |n| 
    n.remove 
end 

這就是如何刪除它們。

p doc.to_xml 
# >> "<span id=\"startsWith_bar\">bar</span>" 
# >> "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body>\n <span id=\"doesnt_start_with\">foo</span>\n \n</body></html>\n" 

頁面「XPath, XQuery, and XSLT Functions」有一個可用功能列表。

+0

你知不知道爲什麼某些函數不起作用(例如 - ends-with())? – taro 2011-05-14 18:51:09

+0

我不知道,Nokogiri使用libxml2,它是一個標準的XML解析器,你應該問一下Nokogiri-談話郵件列表。 – 2011-05-14 22:31:04