From aeee07fdd7f6dcff50c6e1b8ff59423245f2069f Mon Sep 17 00:00:00 2001 From: Hamza Tarar Date: Tue, 17 Nov 2026 01:37:31 +0500 Subject: [PATCH] Escape tab, newline and carriage return in attribute values XML 1.0 section 3.3.3 requires a parser to replace a literal tab, line feed or carriage return in an attribute value with a space before the value reaches the application. REXML wrote those characters literally, so an attribute set to "a\tb" came back as "a b" from any conforming parser, with nothing to report the change. Write them as , and instead, so the value survives the round trip. Verified against expat, which returned the original string only after the change. REXML's own parser does not normalize attribute values, so a REXML to REXML round trip looked correct and hid this. --- lib/rexml/attribute.rb | 9 +++++++++ test/test_attribute.rb | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/lib/rexml/attribute.rb b/lib/rexml/attribute.rb index 2623d29c..0eaa5619 100644 --- a/lib/rexml/attribute.rb +++ b/lib/rexml/attribute.rb @@ -120,6 +120,15 @@ def hash # b.to_string # -> "ns:x='y'" def to_string value = to_s + # A conforming parser normalizes a literal tab, newline or carriage + # return in an attribute value to a space, so write them as character + # references to keep the value intact. See XML 1.0 section 3.3.3. + if value.match?(/[\t\n\r]/) + value = value.gsub(/[\t\n\r]/, + "\t" => " ", + "\n" => " ", + "\r" => " ") + end if @element and @element.context and @element.context[:attribute_quote] == :quote value = value.gsub('"', '"') if value.include?('"') %Q^#@expanded_name="#{value}"^ diff --git a/test/test_attribute.rb b/test/test_attribute.rb index 4928b664..7ddf89c2 100644 --- a/test/test_attribute.rb +++ b/test/test_attribute.rb @@ -29,5 +29,11 @@ def test_to_string_entity document.root.add_attribute("attr", "abc aaa") assert_equal("", document.root.to_s) end + + def test_to_string_whitespace + document = REXML::Document.new("") + document.root.add_attribute("attr", "a\tb\nc\rd") + assert_equal("", document.root.to_s) + end end end