views:

560

answers:

2

I have an XMLDocument that I have read in from file. The file is Unicode, and has the newline character '\n'. When I write the XMLDocument back out, it has the newline characters '\r\n'.

Here is the code, pretty simple:

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

doc.WriteTo(writer);
writer.Close();

XmlWriterSettings has a property, NewLineChars, but I am unable to specify the settings parameter on 'writer', it is read-only.

I can create a XmlWriter with a specified XmlWriterSettings property, but XmlWriter does not have a formatting property, resulting in a file with no linebreaks at all.

So, in short, I need to write a Unicode Xml file with newline character '\n' and Formatting.Indented. Thoughts?

+2  A: 

I think you're close. You need to create the writer from the settings object:

(Lifted from the XmlWriterSettings MSDN page)

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();
Jeff Meatball Yang
Both answers clued me in to what I was missing: settings.Indent = true;
jaws
+2  A: 

Use XmlWriter.Create() to create the writer and specify the format. This worked well:

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();
    }
}
Hans Passant