XmlDocument不读取文件

本文关键字:文件 读取 XmlDocument | 更新日期: 2023-09-27 18:02:26

我试着读xml文件和做一些xml。但我有一个问题加载文件到XmlDocument。这里没有错误。但是当加载时,程序崩溃,编译器说:

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

下面是我的代码:
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "xml (*.xml)|*.xml";
if (dlg.ShowDialog() == true){
XmlDocument doc = new XmlDocument();
doc.Load(dlg.FileName);

XmlDocument不读取文件

文件不是unicode如果你不确定你的编码形式,你可以这样做:

//  path + filename !!
using (StreamReader streamReader = new StreamReader(dlg.FileName, true))
{
    XDocument xdoc = XDocument.Load(streamReader);
}

或者这样做:

XDocument xdoc = XDocument.Parse(System.IO.File.ReadAllLines(dlg.FileName));

仔细阅读链接以理解问题。@ZachBurlingame解决方案;你必须这样做:

为什么c# XmlDocument.LoadXml(字符串)失败时,一个XML头是包括?

// Encode the XML string in a UTF-8 byte array
byte[] encodedString = Encoding.UTF8.GetBytes(xml);
// Put the byte array into a stream and rewind it to the beginning
MemoryStream ms = new MemoryStream(encodedString);
ms.Flush();
ms.Position = 0;
// Build the XmlDocument from the MemorySteam of UTF-8 encoded bytes
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(ms);

它必须工作!