除了我使用 C# 的 XmlSerializer 序列化为 xml 文件的对象列表之外,我还想在同一个 xml 中存储更多独立元素(主要是来自文本框的字符串)。
public static void SaveBehaviors(ObservableCollection<Param> listParams)
{
XmlSerializer _paramsSerializer = new XmlSerializer(listParams.GetType());
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
path += "\\test.xml";
using (TextWriter writeFileStream = new StreamWriter(path))
{
_paramsSerializer.Serialize(writeFileStream, listParams);
using (XmlWriter writer = XmlWriter.Create(writeFileStream))
{
writer.WriteStartElement("Foo"); //test entry...
writer.WriteAttributeString("Bar", "Some & value");
writer.WriteElementString("Nested", "data");
writer.WriteEndElement();
}
}
}
但是,由于添加了元素,反序列化“test.xml”会导致错误。我想在序列化的 xml 文件中写入是禁止的,应该避免吗?