使用特定换行符(c#)将XMLDocument写入文件

使用特定换行符(c#)将XMLDocument写入文件,c#,newline,xmldocument,xmlwriter,C#,Newline,Xmldocument,Xmlwriter,我有一个从文件中读取的XMLDocument。该文件为Unicode,并具有换行符“\n”。当我写回XMLDocument时,它有换行符“\r\n” 下面是代码,非常简单: XmlTextWriter writer = new XmlTextWriter(indexFile + ".tmp", System.Text.UnicodeEncoding.Unicode); writer.Formatting = Formatting.Indented; doc.WriteTo(writer); w

我有一个从文件中读取的XMLDocument。该文件为Unicode,并具有换行符“\n”。当我写回XMLDocument时,它有换行符“\r\n”

下面是代码,非常简单:

XmlTextWriter writer = new XmlTextWriter(indexFile + ".tmp", System.Text.UnicodeEncoding.Unicode);
writer.Formatting = Formatting.Indented;

doc.WriteTo(writer);
writer.Close();
XmlWriterSettings有一个属性NewLineChars,但我无法在“writer”上指定设置参数,它是只读的

我可以使用指定的XmlWriterSettings属性创建XmlWriter,但XmlWriter没有formatting属性,从而导致文件完全没有换行符


因此,简而言之,我需要编写一个带有换行符“\n”和Formatting.Indented的Unicode Xml文件。想法?

我想你很接近了。您需要从设置对象创建编写器:

(摘自页面)

使用XmlWriter.Create()创建编写器并指定格式。这很有效:

using System;
using System.Xml;

class Program {
    static void Main(string[] args) {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.NewLineChars = "\n";
        settings.Indent = true;
        XmlWriter writer = XmlWriter.Create(@"c:\temp\test.xml", settings);
        XmlDocument doc = new XmlDocument();
        doc.InnerXml = "<root><element>value</element></root>";
        doc.WriteTo(writer);
        writer.Close();
    }
}
使用系统;
使用System.Xml;
班级计划{
静态void Main(字符串[]参数){
XmlWriterSettings=新的XmlWriterSettings();
settings.NewLineChars=“\n”;
settings.Indent=true;
XmlWriter=XmlWriter.Create(@“c:\temp\test.xml”,设置);
XmlDocument doc=新的XmlDocument();
doc.InnerXml=“值”;
书面文件(作者);
writer.Close();
}
}

这两个答案都让我明白了我缺少的东西:settings.Indent=true;另请参见:(这里指的是一个答案)
using System;
using System.Xml;

class Program {
    static void Main(string[] args) {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.NewLineChars = "\n";
        settings.Indent = true;
        XmlWriter writer = XmlWriter.Create(@"c:\temp\test.xml", settings);
        XmlDocument doc = new XmlDocument();
        doc.InnerXml = "<root><element>value</element></root>";
        doc.WriteTo(writer);
        writer.Close();
    }
}