Skip to content

Split "]]>" across CDATA sections when writing - #401

Open
Asimmirzac wants to merge 1 commit into
ruby:masterfrom
Asimmirzac:split-cdata-end-marker
Open

Asimmirzac wants to merge 1 commit into
ruby:masterfrom
Asimmirzac:split-cdata-end-marker

Conversation

@Asimmirzac

Copy link
Copy Markdown

A CDATA section ends at the first ]]>, but REXML writes a REXML::CData value as is, so a value containing ]]> produces malformed XML and the content is lost on the next parse:

doc = REXML::Document.new("<script/>")
doc.root.add(REXML::CData.new("if (a[b[0]]>1) {}"))
xml = doc.to_s
# => "<script><![CDATA[if (a[b[0]]>1) {}]]></script>"

reparsed = REXML::Document.new(xml)
reparsed.root.cdatas.map(&:value).join  # => "if (a[b[0"
reparsed.root.texts.map(&:value).join   # => "if (a[b[01) {}]]>"

Python's expat rejects the same output with "not well-formed (invalid token)".

This PR writes each ]]> as ]]]]><![CDATA[>: the section is closed after ]] and a new one starts with >, which is the usual way to put ]]> in CDATA. With the change the example above writes <script><![CDATA[if (a[b[0]]]]><![CDATA[>1) {}]]></script>, REXML and expat both read it back as if (a[b[0]]>1) {}, and the CData value itself is not modified. The splitting is in a small CData.escape_stop helper used by Formatters::Default#write_cdata (so also Pretty and Transitive) and by the deprecated CData#write.

Tests were added in test/formatter/test_default.rb and test/formatter/test_pretty.rb (4 of the 5 fail without the change). ruby test/run.rb passes (886 tests, 0 failures) with Ruby 3.2, also with RUBYOPT=--enable-frozen-string-literal.

Prepared with AI assistance (Claude Code).

🤖 Generated with Claude Code

A CDATA section ends at the first "]]>", so a REXML::CData whose value
contains "]]>" was written as malformed XML: REXML::Document.new on the
output keeps only the part before "]]>" as CDATA and turns the rest into
text, and other parsers (expat, libxml2) reject it.

Write each "]]>" as "]]]]><![CDATA[>" instead, ending the section after
"]]" and opening a new one that starts with ">". Parsers read the sections
back as the original text. The CData value itself is not changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant