为什么xmlreader可以';我没有读到xmlwriter写的东西
本文关键字:xmlwriter 可以 xmlreader 为什么 | 更新日期: 2023-09-27 18:21:32
我有世界上最简单的代码,
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中写一些不同的东西吗?
对此,最简单的解决方案是什么?
您可能没有写入File.WriteAllText
或普通FileStream
无法写入的unicode文件。
相反,使用File.OpenWrite
或FileStream
与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);