XML file processing removes comments
This snippet <!--Please don't delete this-->
is part of my XML file. After running this method, the resulting XML file no longer contains this snippet <!--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();
a source to share
Well, this is quite obvious:
-
XmlSerializer
will parse the XML file and extract all instances from itSettings
- your comment will not be part of any of these objects - when you unsubscribe again, only the contents of the objects will be unloaded again
Settings
Your comment will fall through the cracks, but I don't see any way to save this comment while you are 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 a new file.
a source to share
<!-- -->
means a comment in XML. You are posting an object to XML objects, the objects have no comments as they are compiled at compile time.
That is, the object Settings
(which is probably the de-serialized form of your XML .config) does not store comments in memory after de-serialization, so they will not be serialized either. There is nothing to do with this structure behavior, as the built-in mechanism for de-serializing comments is not used using XmlSerializer
.
a source to share