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.
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With