2011-05-12 49 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