Ok so I am new to C# but a very experienced developer in other langauges but i dont know how to handle if the NodeSelect is nill
DirectoryInfo root = new DirectoryInfo(root_path);
XmlDocument xmlDoc = new XmlDocument(); //* create an xml document object.
xmlDoc.Load(root_path + @"\file.xml"); //* load the XML document from the specified file.
//* Get elements.
XmlNodeList elements = xmlDoc.SelectNodes("//elements");
foreach (XmlNode node in elements){
string link = node.SelectSingleNode("link").InnerText.Trim();
In the above example link may or maynot be in the element block in the xml and i need it to not give me this error
NULLReferenceExemption
Object reference not set to an instance of an object.
I figured a try catch would work but i know there has got to be a better way in C#
UPDATE
var linkNode = node.SelectSingleNode("link");
if (linkNode != null)
{
string link = linkNode.InnerText.Trim();
}
Console.WriteLine("link: " + link);
error is Error
The name 'link' does not exist in the current context
As you say, if the
linknode may or may not be there, you have to test for its existence before accessing its methods and properties.something in the sort of