2013-03-07 73 views
8

我有一個方法中使用的xmlwriter對象。我想把它轉儲到一個文件來讀取它。有沒有一個簡單的方法來做到這一點?寫出xmlwriter到文件

感謝

+0

如果你已經有一個'XmlWriter'的實例,它是不是已經有一個'Stream'('MemoryStream','Fi leStream'等)寫入? – publicgk 2013-03-07 16:39:54

回答

10

使用此代碼

 // Create the XmlDocument. 
     XmlDocument doc = new XmlDocument(); 
     doc.LoadXml("<item><name>wrench</name></item>"); 

     // Add a price element. 
     XmlElement newElem = doc.CreateElement("price"); 
     newElem.InnerText = "10.95"; 
     doc.DocumentElement.AppendChild(newElem); 

     // Save the document to a file and auto-indent the output. 
     XmlTextWriter writer = new XmlTextWriter(@"C:\data.xml", null); 
     writer.Formatting = Formatting.Indented; 
     doc.Save(writer); 

由於在MSDN上找到:http://msdn.microsoft.com/en-us/library/z2w98a50.aspx

+0

+1不知道'Formatting.Indented' – Brad 2013-03-07 16:34:05

3

一種可能性是將XmlWriter的輸出設置爲一個文本文件:

using (var writer = XmlWriter.Create("dump.xml")) 
{ 
    ... 
}