2011-12-15 13 views
4

私はxmlファイルに自分のアプリケーションからいくつかの要素を保存しようとしましたが、私はこのコードを使用して開発を始めたとき:のXmlWriter書込み要素

public static void WriteInFile(string savefilepath) 
     { 
      XmlWriter writer = XmlWriter.Create(savefilepath); 
      WriteXMLFile(writer); 

     } 
private static void WriteXMLFile(XmlWriter writer) //Write and Create XML profile for specific type 
     { 
      writer.WriteStartDocument(); 
      writer.WriteStartElement("cmap"); 
      writer.WriteAttributeString("xmlns", "dcterms",null, "http://purl.org/dc/terms/"); 
      writer.WriteElementString("xmlns", "http://cmap.ihmc.us/xml/cmap/"); 
      // writer.WriteAttributeString("xmlns","dc",null, "http://purl.org/dc/elements/1.1/"); 
      //writer.WriteAttributeString("xmlns", "vcard", null, "http://www.w3.org/2001/vcard-rdf/3.0#"); 
      writer.WriteEndElement(); 
      writer.WriteEndDocument(); 
      writer.Close(); 
     } 

を私はメモ帳で出力を1行であることがわかりましたこのように:

<?xml version="1.0" encoding="utf-8"?><cmap 
xmlns:dcterms="http://purl.org/dc/terms/"><xmlns>http://cmap.ihmc.us/xml/cmap/</xmlns></cmap> 

私はそれがこのような複数行として表示されたい:

<?xml version="1.0" encoding="utf-8"?> <cmap 
xmlns:dcterms="http://purl.org/dc/terms/"><xmlns>http://cmap.ihmc.us/xml/cmap/</xmlns> 
</cmap> 
+0

出力がまったく同じです。 XMLEditorやVisual Studioでロードしてみてください。メモ帳は、その書式設定オプションではわかりません。 –

答えて

10

あなたはCREを持っていますあなたの適切な書式設定オプションを設定したXmlWriterを作成するときにそれを渡す - あなたはXmlWriterSettingsを使用する必要がありますXmlWriterSettings.

XmlWriterSettings settings = new XmlWriterSettings(); 
settings.Indent = true; 
settings.IndentChars = "\t"; 
XmlWriter writer = XmlWriter.Create(savefilepath, settings); 
+6

この問題を抱える今後の読者にとっては、空白を書くことは新しい行/インデントが機能しなくなることに言及する価値があります。 [XmlWriterSettings.Indent](http://msdn.microsoft.com/en-GB/library/system.xml.xmlwritersettings.indent.aspx)のMSDN - "要素は、要素が混在したコンテンツを含まない限りインデントされますWriteStringメソッドまたはWriteWhitespaceメソッドを呼び出して混合要素コンテンツを書き出すと、XmlWriterはインデントを停止します。混在したコンテンツ要素が閉じられるとインデントが再開されます。 – Kobunite

3
XmlWriterSettings settings = new XmlWriterSettings(); 
settings.Indent = true; 
using (var writer = XmlWriter.Create(savefilepath, settings)) 
{ 
    WriteXMLFile(writer); 
} 
関連する問題