Permalink
Browse files

Ensure that all namespaces are inherited from nodes

  • Loading branch information...
1 parent 202cad5 commit b34926caa9648e38ebf25851498c5837189a3313 @benlangfeld committed Nov 18, 2012
Showing with 28 additions and 8 deletions.
  1. +19 −8 lib/niceogiri/xml/node.rb
  2. +9 −0 spec/niceogiri/xml/node_spec.rb
View
@@ -133,18 +133,19 @@ def set_content_for(node, content = nil)
# @param [XML::Node] node the node to inherit
# @return [self]
def inherit(node)
- self.namespace = node.namespace.href if node.namespace
+ inherit_namespaces node
inherit_attrs node.attributes
- node.children.each do |c|
- self << (n = c.dup)
- if c.respond_to?(:namespace) && c.namespace
- ns = n.add_namespace c.namespace.prefix, c.namespace.href
- n.namespace = ns
- end
- end
+ inherit_children node
self
end
+ def inherit_namespaces(node)
+ node.namespace_definitions.each do |ns|
+ add_namespace ns.prefix, ns.href
+ end
+ self.namespace = node.namespace.href if node.namespace
+ end
+
# Inherit a set of attributes
#
# @param [Hash] attrs a hash of attributes to set on the node
@@ -157,6 +158,16 @@ def inherit_attrs(attrs)
self
end
+ def inherit_children(node)
+ node.children.each do |c|
+ self << (n = c.dup)
+ if c.respond_to?(:namespace) && c.namespace
+ ns = n.add_namespace c.namespace.prefix, c.namespace.href
+ n.namespace = ns
+ end
+ end
+ end
+
# The node as XML
#
# @return [String] XML representation of the node
@@ -162,6 +162,15 @@ module XML
body.namespace.href.should be == 'barfoo'
end
+ it 'holds on to prefixed namespaces when inheriting content' do
+ n = Nokogiri::XML.parse('<message xmlns:foo="foobar"></message>').root
+ n.namespaces['xmlns:foo'].should be == 'foobar'
+
+ n2 = Node.new('message').inherit n
+ n2.to_s.should == n.to_s
+ n2.namespaces['xmlns:foo'].should be == 'foobar'
+ end
+
it 'holds on to namespaces without a prefix when inheriting content' do
n = Nokogiri::XML.parse('<message><bar:foo xmlns="http://bar.com"></message>').root
n2 = Node.new('message').inherit n

0 comments on commit b34926c

Please sign in to comment.