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