2013-03-07 72 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")) 
{ 
    ... 
}