簡體   English   中英

XmlDocument無法讀取文件

[英]XmlDocument not reading file

我嘗試讀取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);

該文件不是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解決方案; 您必須執行以下操作:

當包含XML標頭時,為什么C#XmlDocument.LoadXml(string)失敗?

// 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);

它必須工作!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM