tags:

views:

60

answers:

2

Hi,

How do I work with an xml file that when updating it, after saving the commented lines would still be present.

Here's my code snippet for saving the file:

    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();            
    }
A: 

This code will overwrite xml file completely. In order to keep comments in existing file you have to read it first, then update and save.

volody
How do I do it (reading, updating, saving)? Do you have a sample?Is there no other way that I can save the comments? Thanks!
little
as well you can check http://stackoverflow.com/questions/2129414/how-to-insert-xml-comments-in-xml-serialization
volody
(reading, updating, saving) is neccessary if you like to preserve comments done externally (like manual editing)
volody
+3  A: 

I'm not sure I understand you requirement. I would say don't use XmlSerializer because that's designed for creating serialized versions of objects in XML form. Objects don't have XML comments in them, so the XML generated for the object won't generate any comments. If you want to deal with pure XML, just use a simple XML parsing class, rather than one designed for serializing classes as XML documents:

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);
}
BlueMonkMN