1

我有世界上最简单的代码,

using (XmlWriter writer = XmlWriter.Create(stringWriter))
{
 writer.WriteStartDocument();
 writer.WriteStartElement("Board");
 writer.WriteAttributeString("Rows", mRows.ToString());
 writer.WriteAttributeString("Columns", mColumns.ToString());
 writer.WriteEndElement();
 writer.WriteEndDocument();
}
TextWriter writer1 = new StreamWriter(path);
writer1.Write(stringWriter.toString());
writer1.Close();

然后我将它写入一个 txt 文件,如下所示:

<?xml version="1.0" encoding="utf-16"?>
<Board Rows="30" Columns="50">
</Board>

然后我执行以下操作:

FileStream str = new FileStream(s.FileName, FileMode.Open);
using(XmlReader reader = XmlReader.Create(stream))
{
reader.Read();
}

它抛出一个异常:

“没有 Unicode 字节顺序标记。无法切换到 Unicode。”

我搜索了异常并找到了几种解决方法,但我不明白为什么我需要解决方法,我只想阅读我写的 xml。有人可以解释一下到底是什么问题吗?我应该在 xml 中写一些不同的东西吗?

对此最简单的解决方案是什么?

4

1 回答 1

2

您可能没有写入 unicode 文件,File.WriteAllText或者 vanillaFileStream不这样做。

而是使用File.OpenWriteFileStream结合StreamWriter(Stream steam, Encoding encoding)构造函数来指定 unicode。

样本:

var path = @"C:\Dev\sample.xml";

string xml;

var mRows = 30;
var mColumns = 50;

var options = new XmlWriterSettings { Indent = true };

using (var stringWriter = new StringWriter())
{
    using (var writer = XmlWriter.Create(stringWriter, options))
    {
        writer.WriteStartDocument();
        writer.WriteStartElement("Board");
        writer.WriteAttributeString("Rows", mRows.ToString());
        writer.WriteAttributeString("Columns", mColumns.ToString());
        writer.WriteEndElement();
        writer.WriteEndDocument();
    }
    xml = stringWriter.ToString();
}

if(File.Exists(path))
    File.Delete(path);

using(var stream = File.OpenWrite(path))
using(var writer = new StreamWriter(stream, Encoding.Unicode))
{
    writer.Write(xml);
}


Console.Write(xml);

using(var stream = File.OpenRead(path))
using(var reader = XmlReader.Create(stream))
{
    reader.Read();
}

File.Delete(path);
于 2013-07-06T21:15:15.920 回答