2010-04-23 42 views
7

我有從文件讀入的XMLDocument。該文件是Unicode,並具有換行符'\ n'。當我寫回XMLDocument時,它有換行符'\ r \ n'。將XMLDocument寫入具有特定換行符的文件(c#)

下面是代碼,很簡單:

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

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

XmlWriterSettings有一個屬性,NewLineChars,但我無法來指定「作家」的設置參數,它是隻讀的。

我可以使用指定的XmlWriterSettings屬性創建XmlWriter,但XmlWriter沒有格式屬性,導致文件中沒有換行符。

所以,簡而言之,我需要用換行符'\ n'和Formatting.Indented編寫一個Unicode Xml文件。思考?

+0

還看到:http://stackoverflow.com/questions/3415294/how-can-i-generate-xml-with-cr-instead-of-crlf-in-xmltextwriter(其這裏回到一個答案) – 2011-10-06 13:20:18

回答

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(); 
+0

這兩個答案都提示我缺少了什麼:settings.Indent = true; – jaws 2010-04-23 17:41:30

5

使用XmlWriter.Create()創建作家和指定格式。這很適合:

​​
相關問題