0

I read tags for some information in the online dynamic xml file. But an error occurs if the tag I wanna read is not in the xml file. So, I wanna check the xml file. if the tag is in the xml file, start reading xml for the tag. if the tag is not in the xml file, not reading. I am not good in coding c#..

I use this method for reading xml file.

var xmldoc = new XmlDocument();
xmldoc.Load("http://yourwebsite.com/weather.xml");,

temperature.Text = xmldoc.SelectSingleNode("temp").InnerXml.ToString();
windspeed.Text = xmldoc.SelectSingleNode("wind_spd").InnerXml.ToString();
storm.Text = xmldoc.SelectSingleNode("storm").InnerXml.ToString();

The storm tag is sometimes to be in the xml file. Then I can read this time. But when the storm tag is not to be in xml file, I take an error. The code doesn't work.

Shortly, I wanna do this,

if(the storm tag is in xml) //check xml file.
{
 storm.Text = xmldoc.SelectSingleNode("storm").InnerXml.ToString();
}
else
{
    storm.text = "";
}
mvaslan
  • 13
  • 5

2 Answers2

0

You can use null propagation. Something like: temperature.Text = xmldoc.SelectSingleNode("temp")?.InnerXml.ToString(); So in case of xmldoc.SelectSingleNode("temp") returns null - temperature.Text will also be null without exception.

Kantora
  • 111
  • 4
  • Thanks for your comment. But I take a syntax error for 'InnerXml'. as "expected ':' for InnerXml". – mvaslan Jul 01 '17 at 08:44
  • I believe this feature is only available in new versions of the .net framework. You can change your target framework to a newer version or you can add some files to the older frameworks. See this: https://stackoverflow.com/questions/28921701/does-c-sharp-6-0-work-for-net-4-0 – Alexander Higgins Jul 01 '17 at 09:49
0

check for node like this:

var node = xmldoc.SelectSingleNode("storm");
if (node != null)
{
    storm.Text = xmldoc.SelectSingleNode("storm").InnerXml.ToString();
}
else
{
    //node doesn't exist
}
Nino
  • 6,931
  • 2
  • 27
  • 42