2011-01-18 15 views
11

可能性の重複:
How to remove whitespace from an XmlDocument*インデントなしでXmlDocument *を保存する方法はありますか?

すべての私の検索は、反対を尋ねる人を育ててきたが、それは改行で保存されている場合、私は50%近く成長したファイルを持っており、インデント。

これには何らかの方法がありますか?

EDIT私は約開口部ファイルを話していないんだけど、 1を保存します。このコードは、私のための「バグ」を再現:

var path = @"C:\test.xml"; 
System.IO.File.WriteAllText(path, "<root>\r\n\t<line></line>\r\n\t<line></line>\r\n</root>"); 
System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); 
doc.PreserveWhitespace = false; 
doc.Load(path); 
doc.PreserveWhitespace = false; //just in case! 
doc.Save(path); 

真ん中にブレークポイントが期待通りdoc.InnerXmlは、効果的に<root><line></line><line></line></root>であることを示しています。しかし、最後にtest.xmlの内容は次のとおりです。

<root> 
    <line> 
    </line> 
    <line> 
    </line> 
</root> 
+0

http://stackoverflow.com/の可能性のある擬似重複質問/ 2035252/how-to-save-xmldocument-multiple-indentation-settings –

+1

(完全なdup/read対* write *関連) –

答えて

22

このコードを試してみてください。

XmlDocument doc = new XmlDocument(); 

using(XmlTextWriter wr = new XmlTextWriter(fileName, Encoding.UTF8)) 
{ 
    wr.Formatting = Formatting.None; // here's the trick ! 
    doc.Save(wr); 
} 
+0

ありがとう、それはそれを釘付け! – Benjol

+0

Woo、 '<![CDATA [...]]>'ブロックに新しい行を保存します!、ありがとう – Deanna

+0

ありがとう!私は現在、Trados 2014(* .sdlxliff)ファイルのデータを抽出してインポートしていますが、xmlフォーマットを削除せずに保存すると破損しています。 – Cowwando

4

使用XmlWriterSettings

XmlDocument xmlDoc = new XmlDocument(); 
[...] 
XmlWriterSettings xwsSettings = new XmlWriterSettings(); 
xwsSettings.Indent = false; 
xwsSettings.NewLineChars = String.Empty; 
using (XmlWriter xwWriter = XmlWriter.Create(@"c:\test.xml", xwsSettings)) 
xmlDoc.Save(xwWriter); 
+0

これはまた、 '<![CDATA [..]]>'ブロック(余分なスペースではない)の内側から新しい行を取り除くことに注意してください。 – Deanna

関連する問題