问题描述
该段<! - 请不要删除 - >
是我的XML文件的一部分。运行此方法后,生成的XML文件不包含这个片段了<! - 请不要删除 - >
。这是为什么?
下面是我的方法:
XmlSerializer的序列化=新的XmlSerializer(typeof运算(设置));
TextWriter的作家=新的StreamWriter(路径);
serializer.Serialize(作家,设置);
writer.Close();
好了,这是很明显的:
- 的
的XmlSerializer
将解析XML文件,并提取从它的设置的所有实例 - 您的评论不会是任何对象的一部分
当你写那些背出来了,在
设置的唯一的内容
的对象是写出来了
您的评论会漏掉 - 但我看不出有什么办法可以为你使用XmlSerializer办法拯救的评论,只要
。您需要做的是使用的XmlReader / XmlWriter的,而不是:
XmlReader的读者= XmlReader.Create(yourfile.xml);
XmlWriter的作家= XmlWriter.Create(你 - 新file.xml);
而(reader.Read())
{
writer.WriteNode(读者,真正的);
}
writer.Close();
reader.Close();
这将复制所有XML节点 - 包括注释 - 新的文件
。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 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.
这篇关于处理XML文件删除评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!