15

All my searches have brought up people asking the opposite, but I have a file which grows by nearly 50% if it is saved with line returns and indentation.

Is there any way round this?

EDIT I'm not talking about opening a file, but saving one. This code reproduces the 'bug' for me:

var path = @"C:\test.xml";
System.IO.File.WriteAllText(path, "<root>\r\n\t<line></line>\r\n\t<line></line>\r\n</root>");
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.PreserveWhitespace = false;
doc.Load(path);
doc.PreserveWhitespace = false; //just in case!
doc.Save(path);

A breakpoint in the middle shows that doc.InnerXml is effectively <root><line></line><line></line></root>, as expected. But the contents of test.xml at the end is:

<root>
  <line>
  </line>
  <line>
  </line>
</root>
Cœur
  • 37,241
  • 25
  • 195
  • 267
Benjol
  • 63,995
  • 54
  • 186
  • 268

2 Answers2

28

Try this code:

XmlDocument doc = new XmlDocument();

using(XmlTextWriter wr = new XmlTextWriter(fileName, Encoding.UTF8))
{
    wr.Formatting = Formatting.None; // here's the trick !
    doc.Save(wr);
}
digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • Woo, and it preserves new lines in `<![CDATA[...]]>` blocks!, thanks – Deanna May 15 '14 at 14:41
  • Thanks! I am currently extracting and importing back data in Trados 2014 (*.sdlxliff) files and they are breaking if i save them without removing the xml formatting. – Cowwando Jan 08 '16 at 01:55
4

Use XmlWriterSettings:

XmlDocument xmlDoc = new XmlDocument();
[...]
XmlWriterSettings xwsSettings = new XmlWriterSettings();
xwsSettings.Indent = false;
xwsSettings.NewLineChars = String.Empty;
using (XmlWriter xwWriter = XmlWriter.Create(@"c:\test.xml", xwsSettings))
 xmlDoc.Save(xwWriter);
Maxim Gueivandov
  • 2,370
  • 1
  • 20
  • 33
  • Note that this also strips new lines from inside `<![CDATA[..]]>` blocks (but not extra spaces). – Deanna May 15 '14 at 14:38