tags:

views:

60

answers:

2

This snippet <!--Please don't delete this--> is part of my xml file. After running this method, the resulting xml file does not contain this snippet anymore <!--Please don't delete this-->. Why is this?

Here's my method:

         XmlSerializer serializer = new XmlSerializer(typeof(Settings));
         TextWriter writer = new StreamWriter(path);
         serializer.Serialize(writer, settings);
         writer.Close();    
+1  A: 

<!-- --> signifies a comment in XML. You are writing an object out to XML - objects do not have comments as they get compiled out during compilation.

That is, the Settings object (which is probably a de-serialized form of your .config XML) does not hold comments in memory after de-serializing, so they will not get serialized back either. There is nothing you can do about this behavior of the framework as there is no built in mechanism to de-serialize comments using XmlSerializer.

Oded
any other way that i could saved those comments?
little
It depends what you are trying to do - if you just want to copy the file, you can use the approach that @marc_s suggests. If you need to update the settings, you will need to write some custom XML parsing code that will preserve the comments.
Oded
i need to update the xml first.
little
+3  A: 

Well, this is quite obvious:

  • the XmlSerializer will parse the XML file and extract all instances of Settings from it - your comment won't be part of any of those objects
  • when you write those back out again, only the contents of the Settings objects is written out again

Your comment will fall through the cracks - but I don't see any way you could "save" that comment as long as you're using the XmlSerializer approach.

What you need to do is use the XmlReader / XmlWriter instead:

XmlReader reader = XmlReader.Create("yourfile.xml");
XmlWriter writer = XmlWriter.Create("your-new-file.xml");

while (reader.Read())
{
   writer.WriteNode(reader, true);
}

writer.Close();
reader.Close();

This will copy all xml nodes - including comments - to the new file.

marc_s
@marc_s - How would he preserve comments _and_ update changes to the settings using this approach?
Oded
i used the above code and no change was made on the xml file.
little
@oded, @little: well, if you want to modify stuff while read from the original file, you need to parse the XML nodes as you read them. After the call to reader.Read(), you have access to the underlying XML node - you can modify it in any way, shape or form you like.
marc_s