保存一个XML文件,而不
问题描述:
如何与更新它时,注释行储蓄仍然存在之后的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();
}
答
此代码将完全覆盖XML文件。为了保留现有文件中的注释,您必须先阅读它,然后更新并保存。
答
我不知道我理解你的要求。我会说不要使用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);
}
BTW你应该使用'使用(TextWriter的作家=新的StreamWriter(路径)) {serializer.Serialize(writer,settings);}'。即使有例外情况,也能确保作者得到清理。 – 2010-05-09 05:07:09