I have the below xml file:
<Resources>
<a>123.png</a>
</Resources>
<Resources>
<a>Background\345.png</a>
</Resources>
<Resources>
<b>d1.wav</b>
</Resources>
I want to check for the elements to do different function:
foreach (var downloadFile in downloadFiles.Elements("Resources"))
{
if (downloadFile.Element("a").Value != null)
{
// function for a
}
else if (downloadFile.Element("b").Value != null)
{
// function for b
}
}
There will be error " System.NullReferenceException
" when the loop reach element b.
Do you guys know what's wrong?
Looking at your XML, not all resources have the b
element, so you get NRE because Element("b")
returns null. If you want to check whether the element exists compare the Element
to null without accessing Value
property:
if (downloadFile.Element("b") != null)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.