Sunday, 29 September 2013

NullException XML Parsing

NullException XML Parsing

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?
Thanks.

No comments:

Post a Comment