Console.Out 属性和 XmlDocument.Save 方法 (String)

Console.Out 属性

默认情况下,此属性设置为标准输出流。 此属性可以设置为另一个流SetOut方法。

请注意,调用Console.Out.WriteLine方法是等效于调用相应WriteLine方法。

下面的示例使用Out属性显示包含到标准输出设备的应用程序的当前目录中的文件的名称的数组。 然后将标准输出设置为一个名为 Files.txt 文件,并列出了对文件的数组元素。 最后,它将输出设置写入标准输出流,也不会显示数组元素到标准输出设备。

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        // Get all files in the current directory.
        string[] files = Directory.GetFiles(".");
        Array.Sort(files);

        // Display the files to the current output source to the console.
        Console.WriteLine("First display of filenames to the console:");
        Array.ForEach(files, s => Console.Out.WriteLine(s));
        Console.Out.WriteLine();

        // Redirect output to a file named Files.txt and write file list.
        StreamWriter sw = new StreamWriter(@".Files.txt");
        sw.AutoFlush = true;
        Console.SetOut(sw);
        Console.Out.WriteLine("Display filenames to a file:");
        Array.ForEach(files, s => Console.Out.WriteLine(s));
        Console.Out.WriteLine();

        // Close previous output stream and redirect output to standard output.
        Console.Out.Close();
        sw = new StreamWriter(Console.OpenStandardOutput());
        sw.AutoFlush = true;
        Console.SetOut(sw);

        // Display the files to the current output source to the console.
        Console.Out.WriteLine("Second display of filenames to the console:");
        Array.ForEach(files, s => Console.Out.WriteLine(s));

        Console.ReadKey();
    }
}

XmlDocument.Save 方法 (String)

只有当 PreserveWhitespace 设置为 true 时,才在输出文件中保留空白。

当前 XmlDocument 对象的 XmlDeclaration 确定保存的文档的编码属性。编码属性值取自 XmlDeclaration.Encoding 属性。如果 XmlDocument 不具有 XmlDeclaration,或者如果 XmlDeclaration 没有编码属性,则保存的文档也不会有这些属性。

保存文档时,生成 xmlns 属性以正确保持节点标识(本地名称 + 命名空间 URI)。例如,下面的 C# 代码

XmlDocument doc = new XmlDocument();
 doc.AppendChild(doc.CreateElement("item","urn:1"));
 doc.Save(Console.Out);

生成此 xmls 属性 <item xmls="urn:1"/>

该方法是文档对象模型 (DOM) 的 Microsoft 扩展。

using System;
using System.Xml;

public class Sample {

  public static void Main() {
 
    // Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<item><name>wrench</name></item>");

    // Add a price element.
    XmlElement newElem = doc.CreateElement("price");
    newElem.InnerText = "10.95";
    doc.DocumentElement.AppendChild(newElem);

    // Save the document to a file. White space is
    // preserved (no white space).
    doc.PreserveWhitespace = true;
    doc.Save("data.xml");
 
  }
}
原文地址:https://www.cnblogs.com/herizai/p/6970875.html