-2

I am trying to deserialize xml by using the followng code

var reader = new StringReader(uri);
var serializer = new XmlSerializer(typeof(livescore));
var livescores = (livescore)serializer.Deserialize(reader);

where as 'fileToRead' containing a url from where to load xml. But when it tires to deserialize, throws an error

Data at the root level is invalid. Line 1, position 1

I looked a no of post related to this issue, but none of the trick working for me. Any suggestion please?

If I copy the response into a file and read using StreamReader instead of StringReader, it works fine. Not sure, what changes I need to make

Ammar Khan
  • 2,565
  • 6
  • 35
  • 60

1 Answers1

2

The StringReader constructor accepts the string that it shall process, not a file name. Most likely, you are passing in a file name, which in turn the XmlSerializer tries to parse as XML — not the contents of the file but its name. (UPDATE: It's irrelevant whether it's a file name or an URI, the principle is the same.)

Instead, use a StreamReader which accepts a file name in its constructor. Then the rest of your code should work:

var reader = new StreamReader(fileToRead);
var serializer = new XmlSerializer(typeof(livescore));
var livescores = (livescore)serializer.Deserialize(reader);

Also note you should wrap your code into using statements properly to manage your resources properly:

using (var reader = new StreamReader(fileToRead))
{
    … deserialization code goes here …
}

UPDATE Use WebRequest.Create(uri) to create a reader, the retrieve the response using GetResponse. There's a complete example in MSDN here.

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
  • Please see the updated question. My bad I forgot to change the parameter name. I want to read xml from http address. Reading from the file works for me. Now I want to read feed. – Ammar Khan Aug 08 '14 at 17:41
  • That depends on the type of the URI. You can use the `WebRequest` class and its [`Create`](http://msdn.microsoft.com/en-us/library/bw00b1dc(v=vs.110).aspx) method which handles several types of URI. – Ondrej Tucny Aug 08 '14 at 17:42
  • You could also use `XmlReader.Create` which says it takes a URI in the documentation. Then there is another overload of Deserialize that takes an XmlReader. – Mike Zboray Aug 08 '14 at 17:51
  • After using XmlReader, when it tries to deserialize throws an error: {"'', hexadecimal value 0x1F, is an invalid character. Line 1, position 1."} – Ammar Khan Aug 08 '14 at 17:58
  • You should learn to debug your code. Most likely, it's still the same issue: you are confusing a *name / URI* and the actual XML *content*. If you can't figure it out, update or post another question. – Ondrej Tucny Aug 08 '14 at 18:33
  • 1
    OK. That's because when I used XmlReader.Create. After I moved to WebRequest, it does not work either unit I uncompress the xml with GzipStream. Anyway, Thanks for your help and pointing me into right direction. – Ammar Khan Aug 08 '14 at 21:07