Skip to content
Open
Show file tree
Hide file tree
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
13 changes: 12 additions & 1 deletion lib/rexml/cdata.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ class CData < Text
STOP = ']]>'
ILLEGAL = /(\]\]>)/

# A CDATA section can't contain its own end marker, so a "]]>" in the
# content is written by ending the section after "]]" and starting a new
# one with ">". A parser reads the two sections back as the same text.
#
# _Examples_
# CData.escape_stop( "a]]>b" ) # -> "a]]]]><![CDATA[>b"
def self.escape_stop( string )
return string unless string.include?( STOP )
string.gsub( STOP, "]]#{STOP}#{START}>" )
end

# Constructor. CData is data between <![CDATA[ ... ]]>
#
# _Examples_
Expand Down Expand Up @@ -61,7 +72,7 @@ def write( output=$stdout, indent=-1, transitive=false, ie_hack=false )
Kernel.warn( "#{self.class.name}#write is deprecated", uplevel: 1)
indent( output, indent )
output << START
output << @string
output << CData.escape_stop(@string)
output << STOP
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/rexml/formatters/default.rb
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def write_comment( node, output )

def write_cdata( node, output )
output << CData::START
output << node.to_s
output << CData.escape_stop(node.to_s)
output << CData::STOP
end

Expand Down
27 changes: 27 additions & 0 deletions test/formatter/test_default.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,32 @@ def test_content_nil
assert_equal("<?target?>", format(instruction))
end
end

class CDataTest < self
def test_end_marker
cdata = REXML::CData.new("a]]>b")
assert_equal("<![CDATA[a]]]]><![CDATA[>b]]>", format(cdata))
end

def test_multiple_end_markers
cdata = REXML::CData.new("]]>]]]>>")
assert_equal("<![CDATA[]]]]><![CDATA[>]]]]]><![CDATA[>>]]>",
format(cdata))
end

def test_round_trip
element = REXML::Element.new("a")
element.add(REXML::CData.new("if (x[y[0]]>1) {}"))
document = REXML::Document.new(format(element))
assert_equal("if (x[y[0]]>1) {}",
document.root.cdatas.collect(&:value).join)
end

def test_value_is_not_modified
cdata = REXML::CData.new("a]]>b")
format(cdata)
assert_equal("a]]>b", cdata.value)
end
end
end
end
9 changes: 9 additions & 0 deletions test/formatter/test_pretty.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,14 @@ def test_consecutive_spaces_are_squeezed
assert_equal("<a>\n <b>\n x y\n </b>\n</a>", format(document))
end
end

class CDataTest < self
def test_end_marker
document = REXML::Document.new("<a/>")
document.root.add(REXML::CData.new("a]]>b"))
assert_equal("<a>\n <![CDATA[a]]]]><![CDATA[>b]]>\n</a>",
format(document))
end
end
end
end
Loading