0

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

1 Answers1

1

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!

Community
  • 1
  • 1
Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70
  • 1
    XmlDoc should be able to read ASCII and Unicode w/o a BOM. But this might be educational, user3058140 should run it in the debugger. – H H May 09 '14 at 08:44
  • 1
    Check the XML header please do you see something like: – Bassam Alugili May 09 '14 at 08:48
  • 1
    @HenkHolterman it same to be like this problem: http://stackoverflow.com/questions/310669/why-does-c-sharp-xmldocument-loadxmlstring-fail-when-an-xml-header-is-included – Bassam Alugili May 09 '14 at 08:51
  • user can you remove the encoding from the xml this encoding="utf-16 then you do not have to do anything! or you need it? – Bassam Alugili May 09 '14 at 09:05