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();
Well, this is quite obvious:
- the
XmlSerializer
will parse the XML file and extract all instances ofSettings
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.
<!-- -->
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
.
精彩评论