質問

I try read xml file and doing something with xml. But I have a problem with loading a file to XmlDocument. Here isn't error. But when load, program crash and compiler say:

There is no Unicode byte order mark. Cannot switch to Unicode.

Here is my code:

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);
役に立ちましたか?

解決

The file is not unicode If you are not sure form your encoding you can do something like:

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

or do that:

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

Read the link becarefully to understand the problem. @ZachBurlingame solution; You have to do something like that:

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

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

It must working!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top