Skip to content

Commit 37cde3f

Browse files
authored
Accept REXML::Document.new("") for backward compatibility (#295)
## Why? GitHub: Fix GH-296 XML without a root element is invalid XML, but to maintain backward compatibility, we will change the behavior of `REXML::Document.new("")` to be the same as `REXML::Document.new(nil)`. Reported by Joe Rafaniello. Thanks!!!
1 parent 4ffe211 commit 37cde3f

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

lib/rexml/document.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,9 @@ def initialize( source = nil, context = {} )
9595
@entity_expansion_text_limit = Security.entity_expansion_text_limit
9696
super()
9797
@context = context
98-
return if source.nil?
98+
# `source = ""` is an invalid usage because no root element XML is an invalid XML.
99+
# But we accept `""` for backward compatibility.
100+
return if source.nil? or source == ""
99101
if source.kind_of? Document
100102
@context = source.context
101103
super source

test/parse/test_element.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@ def parse(xml)
1414
class TestInvalid < self
1515
def test_top_level_no_tag
1616
exception = assert_raise(REXML::ParseException) do
17-
parse("")
17+
parse(" ")
1818
end
1919
assert_equal(<<-DETAIL.chomp, exception.to_s)
2020
Malformed XML: No root element
21-
Line: 0
22-
Position: 0
21+
Line: 1
22+
Position: 1
2323
Last 80 unconsumed characters:
2424
2525
DETAIL

test/test_core.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1550,6 +1550,26 @@ def test_ticket_138
15501550
REXML::Document.new(doc.root.to_s).root.attributes.to_h)
15511551
end
15521552

1553+
def test_document_with_no_arguments
1554+
assert do
1555+
REXML::Document.new(nil).children.empty?
1556+
end
1557+
end
1558+
1559+
def test_document_with_nil_arguments
1560+
assert do
1561+
REXML::Document.new(nil).children.empty?
1562+
end
1563+
end
1564+
1565+
def test_empty_doc
1566+
# This is an invalid usage because no root element XML is an invalid XML.
1567+
# But we accept `""` for backward compatibility.
1568+
assert do
1569+
REXML::Document.new('').children.empty?
1570+
end
1571+
end
1572+
15531573
private
15541574
def attribute(name, value)
15551575
REXML::Attribute.new(name, value)

0 commit comments

Comments
 (0)