序列化为 XML 文件会创建无效的 XML 文档 (11,12) [英] Serializing to XML file creates invalid XML document (11,12)

查看:20
本文介绍了序列化为 XML 文件会创建无效的 XML 文档 (11,12)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个类保存到一个 XML 文档中.这个类看起来像这样:

I'm trying to save a class into an XML Document. The class looks Like this:

public class Settings
{
    public LDAP LDAP;
    public Miscellaneous Miscellaneous;
}

public class LDAP
{
    public bool LoadLDAPData;
    public bool ShowLDAPRoutingMessage;
}

public class Miscellaneous
{
    public bool MinusBeforeQuestion;
    public bool MinusBeforeDescription;
}

数据通过这个存储:

Settings MySettings = new Settings();
string MySettingsFile = @"settingsfile.xml";
...
FileStream outFile = File.Open(MySettingsFile, FileMode.OpenOrCreate);
XmlSerializer formatter = new XmlSerializer(MySettings.GetType());
formatter.Serialize(outFile, MySettings);
outFile.Close();

数据已保存,但最后有一个问题:

The Data is saved, but with one issue at the end:

<Settings...>
...
</Settings>>>

你能告诉我为什么吗?

推荐答案

发生这种情况是因为您正在编写的内容比文件的现有内容短,因此有些文本留在了末尾.

This is happening because the content you are writing is shorter than the existing contents of the file, so some of the text is left at the end.

代替 FileMode.OpenOrCreate(打开文件并在文件存在时保持其内容不变),使用 FileMode.Create:

Instead of FileMode.OpenOrCreate (which opens the file and leaves its content intact if the file exists), use FileMode.Create:

FileStream outFile = File.Open(MySettingsFile, FileMode.Create);

的描述FileMode.Create:

指定操作系统应该创建一个新文件.如果文件已经存在,它将被覆盖.这需要 FileIOPermissionAccess.Write 权限.FileMode.Create 相当于请求如果文件不存在,则使用CreateNew;否则,使用 Truncate. 如果该文件已存在但为隐藏文件,则抛出 UnauthorizedAccessException 异常.

Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.

这篇关于序列化为 XML 文件会创建无效的 XML 文档 (11,12)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆