Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Nokogiri::XML::Document#collect_namespaces_[href_keys|prefix_keys] #1001

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions lib/nokogiri/xml/document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,56 @@ def collect_namespaces
end
end

##
# In order to collect all namespaces in a document with
# multiple default namespace definitions use either
# collect_namespaces_prefix_keys or collect_namespaces_href_keys
#
# For example, given this document:
#
# <?xml version="1.0"?>
# <foo xmlns="foospace">
# <bar xmlns="barspace"/>
# </foo>
#
# collect_namespaces_prefix_keys will return a hash with
#
# {"xml"=>["http://www.w3.org/XML/1998/namespace"], nil=>["foospace", "barspace"]}
#
# where nil implies xmlns.
#
def collect_namespaces_prefix_keys
xpath("//namespace::*").inject({}) do |hash, ns|
(hash[ ns.prefix ] ||= []) << ns.href unless (hash[ ns.prefix ] and hash[ ns.prefix ].include? ns.href)
hash
end
end

##
# In order to collect all namespaces in a document with
# multiple default namespace definitions use either
# collect_namespaces_prefix_keys or collect_namespaces_href_keys
#
# For example, given this document:
#
# <?xml version="1.0"?>
# <foo xmlns="foospace">
# <bar xmlns="barspace"/>
# </foo>
#
# collect_namespaces_href_keys will return a hash with
#
# {"http://www.w3.org/XML/1998/namespace"=>["xml"], "foospace"=>[nil], "barspace"=>[nil]}
#
# where nil implies xmlns.
#
def collect_namespaces_href_keys
xpath("//namespace::*").inject({}) do |hash, ns|
(hash[ ns.href ] ||= []) << ns.prefix unless (hash[ ns.href ] and hash[ ns.href ].include? ns.prefix)
hash
end
end

# Get the list of decorators given +key+
def decorators key
@decorators ||= Hash.new
Expand Down