How can I add a custom XPath function for class check to Nokogiri?
I.e. something like https://gist.github.com/knu/087b7f89bb31de4f419c, but performing
contains(concat(' ',normalize-space(@class),' '),' #{class_name} ')
Thanks :)
CodePudding user response:
The following seems to work:
require 'nokogiri'
require 'singleton'
class CustomFunctions
include Singleton
# Implements: contains(concat(' ',normalize-space(@class),' '),' #{class_name} ')
def contains_class(nodeset, class_name)
nodeset.any? do |node|
attribute_value = node['class']
!attribute_value.nil? && attribute_value.split(' ').include?(class_name)
end
end
alias_method :'contains-class', :contains_class
module SetDefaultHandler
private
def extract_params(args)
params = super
params[1] ||= CustomFunctions.instance
params
end
Nokogiri::XML::Node.prepend self
Nokogiri::XML::NodeSet.prepend self
end
end
xml = Nokogiri::XML('<html><body><div >ascabsc</div><div >zjtzj</div></body></html>')
xml.root.add_namespace('fn', 'http://www.w3.org/2005/xpath-functions')
%w[a2 a3].each do |class_name|
puts "Test #{class_name}: " xml.xpath(".//div[fn:contains-class(., \"#{class_name}\")]").to_s
end