2010-05-09 86 views
0

如何与更新它时,注释行储蓄仍然存在之后的XML文件的工作。保存一个XML文件,而不

这是我保存文件的代码片段:

public static void WriteSettings(Settings settings, string path) 
    { 
     XmlSerializer serializer = new XmlSerializer(typeof(Settings)); 
     TextWriter writer = new StreamWriter(path); 
     serializer.Serialize(writer, settings); 
     writer.Close();    
    } 
+0

BTW你应该使用'使用(TextWriter的作家=新的StreamWriter(路径)) {serializer.Serialize(writer,settings);}'。即使有例外情况,也能确保作者得到清理。 – 2010-05-09 05:07:09

回答

0

此代码将完全覆盖XML文件。为了保留现有文件中的注释,您必须先阅读它,然后更新并保存。

+0

我怎么做(读取,更新,保存)? 你有一个样本? 难道就没有别的办法,我可以节省的评论? 谢谢! – little 2010-05-09 05:21:53

+0

也可以检查http://stackoverflow.com/questions/2129414/how-to-insert-xml-comments-in-xml-serialization – volody 2010-05-09 06:09:29

+0

(读取,更新,保存)是neccessary如果你想保留做过评论外部(如手动编辑) – volody 2010-05-09 06:18:23

3

我不知道我理解你的要求。我会说不要使用XmlSerializer,因为它被设计用于以XML形式创建对象的序列化版本。对象中没有XML注释,因此为该对象生成的XML将不会生成任何注释。如果你想对付纯粹的XML,只需使用一个简单的XML解析类,而不是一个专为序列化类作为XML文档:

string myXml = 
    "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine + 
    "<!-- This is a comment -->" + Environment.NewLine + 
    "<Root><Data>Test</Data></Root>"; 

System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); 
xml.PreserveWhitespace = true; 
xml.LoadXml(myXml); 
var newElem = xml.CreateElement("Data"); 
newElem.InnerText = "Test 2"; 
xml.SelectSingleNode("/Root").AppendChild(newElem); 
System.Xml.XmlWriterSettings xws = new System.Xml.XmlWriterSettings(); 
xws.Indent = true; 
using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(Console.Out, xws)) 
{ 
    xml.WriteTo(xw); 
}