Sangram Nandkhile
Sangram Nandkhile

Reputation: 18192

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.

Upvotes: 44

Views: 45300

Answers (3)

Sangram Nandkhile
Sangram Nandkhile

Reputation: 18192

I tried , and found another way of doing it !!

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

Upvotes: 10

hamidreza samsami
hamidreza samsami

Reputation: 419

This code:

System.IO.File.ReadAllLines(path)

returns an array of strings. The correct code is:

System.IO.File.ReadAllText(path)

Upvotes: 7

Randy Levy
Randy Levy

Reputation: 22655

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

Upvotes: 68

Related Questions