The ramblings of a disgruntled geek!!

Wednesday, January 28, 2009

XmlTextReader fiasco



I hit a snag a few days ago while doing some Xml parsing in one of my applications.

I am using XDocument for Xml parsing(XLinq is beautiful (K)).

Doing XDocument.Load(urlString) or XmlTextReader() would make my application choke with an Xml parsing error (invalid character). Using StreamReader to wrap the actual stream (WebResponse.GetResponseStream) and passing it to XDocument works like a charm. I wrote a sample app to figure out the issue and it turns out that XmlTextReader is the culprit. Maybe it fails to correctly recognize UTF-8 markers, or maybe it's stricter than other Readers, it didn't work for me. So beware. :)

Code Snippet (fails):
WebRequest req = WebRequest.Create("");
WebResponse res = req.GetResponse();
XmlTextReader reader = new XmlTextReader(res.GetResponseStream());
XDocument xdoc = XDocument.Load(reader, LoadOptions.SetLineInfo); //LoadOptions.SetLineInfo helps with debugging.

Code Snippet (works):
WebRequest req = WebRequest.Create("");
WebResponse res = req.GetResponse();
StreamReader reader = new StreamReader(res.GetResponseStream());
XDocument xdoc = XDocument.Load(reader, LoadOptions.SetLineInfo); //LoadOptions.SetLineInfo helps with debugging.


Happy XLinq-ing.

Keyboard

Keyboard
Keyboard

Blog Reading Level

blog readability test

VerveEarth

About Me

My photo

Alpha Geek. 
Aspiring Entrepreneur.