2011-12-15 63 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(); 
     } 

我發現,在記事本中的輸出是一個行像這樣:

<?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中加載它。記事本不知道其格式選項。 – 2011-12-15 14:28:32

回答

10

你有CRE吃的XmlWriterSettings.

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

值得一提的是,對於這個問題的任何未來的讀者來說,編寫一個空格將停止新的行/縮進工作。 [XmlWriterSettings.Indent]的MSDN(http://msdn.microsoft.com/en-GB/library/system.xml.xmlwritersettings.indent.aspx) - 「只要元素不包含混合內容,元素就會縮進。一旦調用WriteString或WriteWhitespace方法寫出混合元素內容,XmlWriter將停止縮進。一旦混合內容元素關閉,縮進將恢復。 – Kobunite 2013-05-02 13:44:47

3
XmlWriterSettings settings = new XmlWriterSettings(); 
settings.Indent = true; 
using (var writer = XmlWriter.Create(savefilepath, settings)) 
{ 
    WriteXMLFile(writer); 
}