Search code examples
c#xmldocument

Save XML file without formatting


I have a XML file that needs to be saved without formatting, without identation and line breaks. I'm doing it this way:

using (var writer = System.IO.File.CreateText("E:\\nfse.xml"))
{
    var doc = new XmlDocument { PreserveWhitespace = false };
    doc.Load("E:\\notafinal.xml");
    writer.WriteLine(doc.InnerXml);
    writer.Flush();
}

But that way I need to create the file, and then I need to change it 3 times, so in the end there are a total of 4 files, the initial one and the result of the 3 changes.

When I save the file, I do it this way:

 MemoryStream stream = stringToStream(soapEnvelope);
 webRequest.ContentLength = stream.Length;
 Stream requestStream = webRequest.GetRequestStream();
 stream.WriteTo(requestStream);

 document.LoadXml(soapEnvelope);
 document.PreserveWhitespace = false;
 document.Save(@"E:\\notafinal.xml");

How can I do this without having to create a new document?


Solution

  • If what you want is to eliminate extra space by not formatting the XML file, you could use XmlWriterSettings and XmlWriter, like this:

    public void SaveXmlDocToFile(XmlDocument xmlDoc,
                                 string outputFileName,
                                 bool formatXmlFile = false)
    {
       var settings = new XmlWriterSettings();
       if (formatXmlFile)
       {
          settings.Indent = true;
       }
       else
       {
          settings.Indent = false;
          settings.NewLineChars = String.Empty;
       }
       using (var writer = XmlWriter.Create(outputFileName, settings))
          xmlDoc.Save(writer);
    }
    

    Passing formatXmlFile = false in the parameters will save the XML file without formatting it.