renggli / dart-xml

Lightweight library for parsing, traversing, and transforming XML in Dart.
http://pub.dartlang.org/packages/xml
MIT License
223 stars 52 forks source link

.toXmlString(pretty: true) should not replace \r\n with spaces #149

Closed gaddlord closed 2 years ago

gaddlord commented 2 years ago

.toXmlString(pretty: true) converts \r\n in the text of elements to spaces. I believe this behavior is wrong - text inside elements should not be touched by prettification.

test('Saving elements with new lines', () {
  final document = XmlBuilder();
  document
    ..processing('xml', 'version="1.0"')
    ..element(
      'test',
      nest: () {
        document.text('a\r\nb');
      },
    );

  expect(
    document.buildDocument().toXmlString(pretty: true),
    '<?xml version="1.0"?>\n<test>a\r\nb</test>',
  );
});

The test fails returning

<?xml version="1.0"?>
<test>a b</test>
renggli commented 2 years ago

If whitespaces cannot be touched, there is little the pretty printer can do to make the XML look pretty.

You can protect parts of the document by providing a preserveWhitespace predicate. In your example you could tell the pretty printer not to touch the inside of the <test> node:

document.toXmlString(
    pretty: true, 
    preserveWhitespace: (node) => node is XmlElement && node.localName == 'test',
);
gaddlord commented 2 years ago

That did the trick. Yet I am still under the impression that Pretty Print should be used more as a Formatter of the XML document and not amend the Attribute/Elements text.