-1

Language C# in Forms.

I'm trying to change a label to some xml data that I retrieved, but it I get the error that it can't convert it to a string. It's confusing since im reading it as a string?

I already tried it out in a console project, it works fine there:

Code in Console :

String URLString = "http://query.yahooapis.com/v1/public/yql?...

XmlTextReader reader = new XmlTextReader(URLString);

reader.ReadStartElement("Bid");
Console.Write("YAHOO's current bid price: ");
Console.WriteLine(reader.ReadString());
reader.ReadEndElement();

Code in Forms:

String URLString = "http://query.yahooapis.com/v1/public/yql?...

XmlTextReader reader = new XmlTextReader(URLString);

reader.ReadToFollowing("Bid");
reader.ReadStartElement("Bid");
lblBidPrice.Text = Convert.ToString(reader.ReadString());
reader.ReadEndElement();
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • 1
    There are difference between two snippets you have provided. – Hamlet Hakobyan Jan 21 '14 at 23:12
  • 1
    Your code is different in both examples... I would assume the problem is in `reader.ReadToFollowing("Bid")` since it is missing from your Console program. Can you post the exact error and what line it is generated from please? – Evan L Jan 21 '14 at 23:12
  • 1
    The code works fine if there is a `` element in XML. Post the sample XML you're trying to parse. – Szymon Jan 21 '14 at 23:13
  • 1
    The Original Poster said, "I get the error that it can't convert it to a string". What is "it" and what, exactly, is the error you're getting? We need a problem statement to help you. – Nicholas Carey Jan 21 '14 at 23:37
  • This `Convert.ToString(reader.ReadString());` definitely makes no sencse. `reader.ReadString` already returns string. – T.S. Jan 21 '14 at 23:40
  • The problem solved it self after some restarts of Visual Studio, makes no sense no changes to the code was needed. Thanks any way, extremly good response. – MattiasLarsson Feb 19 '14 at 14:00

1 Answers1

0

This works perfectly fine:

string xml = @"<?xml version=""1.0""?>
<Bid>
  This is bid content
</Bid>
" ;
StringReader sr = new StringReader(xml) ;
XmlReader reader = XmlReader.Create(sr) ;
reader.MoveToContent() ;
reader.ReadStartElement("Bid");
string content = Convert.ToString(reader.ReadString()) ;
Console.WriteLine( content ) ;
reader.ReadEndElement();

producing the output you'd expect (though why you'd feel a need to try to convert a string to a string is beyond me):

  This is bid content

with the additional leading/trailing linebreaks you'd expect.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • It worked fine for me too but I'm not sure if that can be an asnwer. I think we're missing some information from the asker here. – Szymon Jan 21 '14 at 23:50