我有一个我从文件中读过的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'上指定settings参数,它是只读的。
我可以使用指定的XmlWriterSettings属性创建XmlWriter,但XmlWriter没有格式化属性,导致文件根本没有换行符。
因此,简而言之,我需要编写一个带有换行符'\ n'和Formatting.Indented的Unicode Xml文件。想法?
答案 0 :(得分:5)
我觉得你很亲密。您需要从设置对象创建编写器:
(摘自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();
答案 1 :(得分:5)
使用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();
}
}