Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading xml with encoding UTF 16 using XDocument

I am trying to read the xml document using XDocument method . but i am getting an error when xml has

<?xml version="1.0" encoding="utf-16"?> 

When i removed encoding manually.It works perfectly.

I am getting error " There is no Unicode byte order mark. Cannot switch to Unicode. "

i tried searching and i landed up here-->

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

But could not solve my problem.

My code :

XDocument xdoc = XDocument.Load(path); 

Any suggestions ??

thank you.

like image 921
Sangram Nandkhile Avatar asked Dec 31 '10 07:12

Sangram Nandkhile


People also ask

Does XML support UTF-16?

If you type an XML document into Notepad, you can choose from one of several supported character encodings including ANSI, UTF-8, or UTF-16.

How do I change the encoding of an XML file?

Another way to change the encoding of an XML document is to directly edit the encoding attribute of the document's XML declaration. Default encodings for existing and new XML and non-XML documents can be set in the Encoding section of the Options dialog.

What is UTF-16 in XML?

UTF stands for UCS Transformation Format, and UCS itself means Universal Character Set. The number 8 or 16 refers to the number of bits used to represent a character. They are either 8(1 to 4 bytes) or 16(2 or 4 bytes). For the documents without encoding information, UTF-8 is set by default.


1 Answers

It looks like the file you are trying to read is not encoded as Unicode. You can replicate the behavior by trying to open a file encoded as ANSI with the encoding in the XML file specified as utf-16.

If you can't ensure that the file is encoded properly, then you can read the file into a stream (letting the StreamReader detect the encoding) and then create the XDocument:

using (StreamReader sr = new StreamReader(path, true)) {     XDocument xdoc = XDocument.Load(sr); } 
like image 139
Randy supports Monica Avatar answered Oct 12 '22 10:10

Randy supports Monica