有没有办法用FileStream编写一个没有BOM的流? 我在这里做的是首先将XmlNode转换为Stream并在稍后将该流写入文件。我需要它以Stream的形式才能与我的功能互操作。我可以用另一种方式做到这一点,但如果可能的话,我想这样做。
Stream^ XmlToStream(XmlNode^ Node)
{
Stream^ stream = gcnew MemoryStream();
XmlDocument^ xmlDoc = gcnew XmlDocument();
xmlDoc->PreserveWhitespace = true;
xmlDoc->LoadXml(Node->OuterXml);
xmlDoc->Save(stream);
//OR THIS:
//TODO: Handle exceptions
// XmlWriterSettings^ settings = gcnew XmlWriterSettings();
// settings->Encoding = System::Text::Encoding::UTF8;
// settings->OmitXmlDeclaration = true;
// settings->NewLineChars = "\n";
// XmlWriter^ xwriter = XmlWriter::Create(stream, settings);
// Node->WriteTo(xwriter);
// xwriter->Close();
return stream;
}
void StreamToFile(Stream^ DataStream, String^ FilePath)
{
FileStream^ fileStream = gcnew FileStream(FilePath, FileMode::Create);
if (DataStream->CanSeek)
{
DataStream->Seek(0, SeekOrigin::Begin);
}
DataStream->CopyTo(fileStream);
fileStream->Close();
}
答案 0 :(得分:2)
您正在获取BOM,因为通过写入MemoryStream,框架不知道正确的编码应该是什么。所以它在XmlDocument的编码方面付出了代价,默认情况下它是utf-8。这也会生成BOM。
要控制它,您需要将TextWriter对象传递给XmlDocument :: Save()方法。这可以是StreamWriter,后者又写入MS。默认情况下,StreamWriter也会在utf-8中进行编码,但除非您明确询问,否则不会生成BOM。像这样:
Stream^ XmlToStream(XmlNode^ Node)
{
auto stream = gcnew MemoryStream();
auto writer = gcnew StreamWriter(stream);
//...
xmlDoc->Save(writer);
writer->Flush();
return stream;
}