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

8

我有一个从文件中读取的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没有格式化属性,导致文件完全没有换行符。

所以,简而言之,我需要编写一个带有换行符'\n'和Formatting.Indented的Unicode Xml文件。你有什么想法吗?


请参见:https://dev59.com/KU_Ta4cB1Zd3GeqPB5KA(该链接指向此处的一个答案) - Michael Paulukonis
2个回答

6

我认为你已经接近正确答案了。你需要从设置对象中创建写入器:

(摘自XmlWriterSettings MSDN页面)

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
settings.NewLineOnAttributes = true;

writer = XmlWriter.Create(Console.Out, settings);

writer.WriteStartElement("order");
writer.WriteAttributeString("orderID", "367A54");
writer.WriteAttributeString("date", "2001-05-03");
writer.WriteElementString("price", "19.95");
writer.WriteEndElement();

writer.Flush();

两个答案都让我明白了我所缺少的东西:settings.Indent = true; - jaws

6

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接