Reputation: 1268
I'm having a problem with parsing XML in C#, my XML file looks like this:
<xml>
<category>books</category>
<id>1</id>
<title>lemony</title>
<sub>
<title>lemonyauthor</title>
</sub>
</xml>
<xml>
<category>comics</category>
<id>2</id>
<sub>
<title>okauthor</title>
</sub>
</xml>
As you can see sometimes the title in "XML" is returned, sometimes not.
My code in C# to parse this looks like:
string _Title;
foreach (XElement str in xmlDoc.Descendants("xml"))
{
_Title = "";
if (str.Element("title").Value != null)
_Title = str.Element("title").Value;
foreach (XElement cha in str.Descendants("sub"))
{
if (_Title.Length < 1 && cha.Element("Title").Value != null)
_Title = cha.Element("title").Value;
}
}
How do I keep the line if (str.Element("category").Value != null)
from returning a NullException
?
Is using try
& catch
the only way?
Upvotes: 0
Views: 76
Reputation: 35901
Change this:
if (str.Element("title").Value != null)
_Title = str.Element("title").Value;
to this:
var titleElement = str.Element("title");
if (titleElement != null)
_Title = titleElement.Value;
Upvotes: 2
Reputation: 137148
If you are expecting str.Element("title")
(which is the most likely cause of of the exception) to be null (no matter how occasionally) then you should have a test for that:
if (str.Element("title") != null)
{
// your existing code.
}
If you are not expecting it to be null and it truly is an exceptional circumstance then having a try catch is the only other way to stop the method crashing.
Upvotes: 3