diff --git a/lib/nokogiri/xml/document_fragment.rb b/lib/nokogiri/xml/document_fragment.rb index 7cf03773c9..af4450c082 100644 --- a/lib/nokogiri/xml/document_fragment.rb +++ b/lib/nokogiri/xml/document_fragment.rb @@ -51,7 +51,11 @@ def to_xml *args ### # Search this fragment. See Nokogiri::XML::Node#css def css *args - children.css(*args) + if children.any? + children.css(*args) + else + NodeSet.new(document) + end end alias :serialize :to_s diff --git a/lib/nokogiri/xml/fragment_handler.rb b/lib/nokogiri/xml/fragment_handler.rb index 68e046c14d..06f63e645b 100644 --- a/lib/nokogiri/xml/fragment_handler.rb +++ b/lib/nokogiri/xml/fragment_handler.rb @@ -28,13 +28,15 @@ def start_element name, attrs = [] @doc_started = true if @original_html =~ regex return unless @doc_started - if @document.root and match = name.match(QNAME_REGEX) - prefix, name = match[1], match[2] - ns = @document.root.namespace_definitions.detect { |x| - x.prefix == prefix - } - else - ns = nil + ns = nil + if @document.root + match = name.match(QNAME_REGEX) + if match + prefix, name = match[1], match[2] + ns = @document.root.namespace_definitions.detect { |x| + x.prefix == prefix + } + end end node = Element.new(name, @document) diff --git a/test/html/test_document_fragment.rb b/test/html/test_document_fragment.rb index e6f66ba40b..55a249999f 100644 --- a/test/html/test_document_fragment.rb +++ b/test/html/test_document_fragment.rb @@ -39,6 +39,16 @@ def test_fragment_should_have_document assert_equal @html, fragment.document end + def test_empty_fragment_should_be_searchable_by_css + fragment = Nokogiri::HTML.fragment("") + assert_equal 0, fragment.css("a").size + end + + def test_empty_fragment_should_be_searchable + fragment = Nokogiri::HTML.fragment("") + assert_equal 0, fragment.search("//a").size + end + def test_name fragment = Nokogiri::HTML::DocumentFragment.new(@html) assert_equal '#document-fragment', fragment.name