保存 XML 文件而不格式化 [英] Save XML file without formatting

查看:56
本文介绍了保存 XML 文件而不格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XML 文件,需要在没有格式、没有标识和换行的情况下保存.我是这样做的:

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();
}

但是这样我需要创建文件,然后我需要更改它3次,所以最终总共有4个文件,最初的一个和3次更改的结果.

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?

推荐答案

如果您想通过不格式化 XML 文件来消除额外空间,您可以使用 XmlWriterSettingsXmlWriter,像这样:

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);
}

在参数中传递 formatXmlFile = false 将保存 XML 文件而不对其进行格式化.

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

这篇关于保存 XML 文件而不格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆