Writing XMLDocument to a file with a specific newline character (C #)

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

Here is the code, quite simple:

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

XmlWriterSettings has the NewLineChars property, but I cannot specify the parameter parameter in 'writer', it is read-only.

I can create an XmlWriter with the specified XmlWriterSettings property, but XmlWriter does not have a formatting property, leaving the file without any line breaks.

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

+7
c # newline xmldocument xmlwriter
source share
2 answers

I think you're around. You need to create an entry from the settings object:

(taken 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(); 
+5
source share

Use XmlWriter.Create () to create an entry 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(); } } 
+5
source share

All Articles