Save XML file without formatting

Deadly 提交于 2019-12-11 19:47:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/53518785/save-xml-file-without-formatting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!