如何用C#DataSet中的漂亮打印来编写XML

Tim*_*ter 8 c# xml

在C#中,如果没有使用漂亮的打印文件,你如何编写一个DataSet文件?

使用C#和.NET 2.0,我一直在使用dataSet.WriteXml(fileName,XmlWriteMode.IgnoreSchema),默认情况下是使用漂亮的打印来编写Xml文件.使用我写的Xml文件的公司建议,没有漂亮打印的写入不会影响它们,并且会显着减小文件的大小.稍微在System.Xml命名空间中玩,我找到了一个解决方案.但是,在我的搜索中,我没有在任何地方找到答案,所以我认为如果我发布问题,将来可能对其他人有所帮助.此外,如果有更好或至少不同的方式来实现这一点,我不会感到惊讶.

对于那些不知道的人(直到今天我都没有),Xml"漂亮的印刷品"是:

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <Foo>
    <Bar>abc</Bar>
  </Foo>
</NewDataSet>
Run Code Online (Sandbox Code Playgroud)

没有漂亮的打印,它看起来像这样:

<?xml version="1.0" encoding="utf-8"?><NewDataSet><Foo><Bar>abc</Bar></Foo></NewDataSet>
Run Code Online (Sandbox Code Playgroud)

此外,大小节省是显着的,70mb文件正在变得大约40mb.如果没有其他人的话,我今天晚些时候会发布我的解决方案.

cas*_*One 8

这很简单,你只需要创建一个XmlWriter使用XmlWriterSettings它具有Indent属性设置为false:

// The memory stream for the backing.
using (MemoryStream ms = new MemoryStream())
{
  // The settings for the XmlWriter.
  XmlWriterSettings settings = new XmlWriterSettings();

  // Do not indent.
  settings.Indent = false;

  // Create the XmlWriter.
  using (XmlWriter xmlWriter = XmlWriter.Create(ms, settings))
  {
     // Write the data set to the writer.
     dataSet.WriteXml(xmlWriter);
  }
}
Run Code Online (Sandbox Code Playgroud)


ats*_*joo 6

比使用XmlWriterSettings更容易:

XmlTextWriter xml = new XmlTextWriter(fileName, Encoding.UTF8) 
    { Formatting = Formatting.None };
dataSet.WriteXml(xml);
Run Code Online (Sandbox Code Playgroud)