44

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.

3 Answers 3

68

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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

I have my the output of XML being spit into html. The above solution did not work for me. I have a copyright symbol (c) in my text of the xml document and it always gets garbled when the HTML comes to the browser. So I tried to encode (XML encode the HTML encoded string) but it literally comes out as it is in HTML. i.e. &amp;copy; in xml literally comes out as &amp;copy; instead of the expected &copy; so that the browser can display the (c).
10

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

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

7 Comments

Wow! This is new, 4.5 was just released! (2012-08-15 - 5 days ago) :) Way to stay up on your framework Sangram!
From what I can tell the XDocument.Parse() method was new and just introduced to .Net 4.5 framework. That was released on 2012-08-15 which at the time was 5 days ago... It was simply a complement, usually people just say thanks for a complement. :P
Okay. Thanks for that :) but i think existed from 3.5 because i am still using 3.5 :P check msdn.microsoft.com/en-us/library/…
This doesn't compile for me as the Parse method accepts a string and the ReadAllLines method returns a string array! Shouldn't it be ReadAllText?
XDocument.Parse expects a string, so File.ReadAllLines doesn't compile. You have to use File.ReadAllText. At least, that's how it's working for me in VS2017.
|
7

This code:

System.IO.File.ReadAllLines(path) 

returns an array of strings. The correct code is:

System.IO.File.ReadAllText(path) 

1 Comment

okay. that's another way to do it. but readAllLines does work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.