Skip to content

Instantly share code, notes, and snippets.

@knu
Created September 1, 2015 13:16
Show Gist options
  • Save knu/087b7f89bb31de4f419c to your computer and use it in GitHub Desktop.
Save knu/087b7f89bb31de4f419c to your computer and use it in GitHub Desktop.
Defining custom XPath functions in Nokogiri
require 'nokogiri'
require 'singleton'
class CustomFunctions
include Singleton
# Implements fn:string-join of XPath 2.0
def string_join(nodeset, separator)
nodeset.map(&:text).join(separator)
end
alias_method :'string-join', :string_join
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(ARGF.read)
xml.root.add_namespace('fn', 'http://www.w3.org/2005/xpath-functions')
puts xml.xpath('normalize-space(fn:string-join(.//text(), ":"))')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment