Created
September 1, 2015 13:16
-
-
Save knu/087b7f89bb31de4f419c to your computer and use it in GitHub Desktop.
Defining custom XPath functions in Nokogiri
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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