Hi Doug,
The reason for the compiler error is pointed out below
On Wed, 17 Jan 2007 09:51:26 +0100, Doug <go**********@optusnet.com.au
wrote:
Hi
I have a method that I would like to return the value to the calling
event.
I have a bad example below that doesnt give me what I want.
What I want is to have a my readxml mthod return the value of a string
in an
xml file if that element is in the xml file - but a message saying that
the
string doesnt exist if it is not there.
I have used a method that should return a string, but it doesn't work-
even
though the string is in the xml file. I often get an error that not all
code paths return a value. If you can fix my code to avoid this error
please help.
public string readxml()
{
XmlTextReader tr = null;
tr = new XmlTextReader(xmlFilename);
while (tr.Read())
{
if (tr.NodeType == XmlNodeType.Element)
{
if (tr.LocalName.Equals("location"))
{
return tr.ReadString();
}
if tr.LocalName is not equal to location it will continue the loop, but
once the loop is over, there is no return
}
else
{
return "Nothing here";
}
tr.Close();
}
put return "Nothing here" as well. If you have abunch of valid xml
elements, but none that are called "location" you will get to this step.
}
thanks for you assistance
Doug
Summing up, the method should look like something like this (nb! haven't
tested the logic). I've taken the liberty to put the XmlTextReader inside
a using block which will automatically close it once you are finished with
it
public string readxml()
{
using (XmlTextReader tr = new XmlTextReader(xmlFilename))
{
while (tr.Read())
{
if (tr.NodeType == XmlNodeType.Element)
{
if (tr.LocalName.Equals("location"))
{
return tr.ReadString();
}
}
else
{
return "Nothing here";
}
}
}
return "Nothing here";
}
Beware that your code will return once it encounters a single non element
node and you may be better off not returning in the else at all, but
traverse all nodes and return at the end of the method.
--
Happy Coding!
Morten Wennevik [C# MVP]