Why Is XDocument.Descendants().Count() > 0 for an Empty Document?
Here's my method:
var document = XDocument.Parse(source);
if (document.Descendants().Count() > 0)
{
// Some code that shouldn't execute
}
else
{
// Code that should execute
}
This co开发者_C百科de breaks when this is in the 'document' variable:
<ipb></ipb>
Since this DOESN'T have descendants, why is it entering the IF conditional? Is shouldn't try to load anything, yet it does and breaks when it finds nothing to scrape.
Using Breakpoints I can confirm that the document variable has the content I posted above when it breaks and it does enter the if.
Have you tried using:
document.Root.Descendants().Count() > 0;
The Root element sits below the XDocument.
ipb
is your first descendant on the document, right? Don't you want document.Root.Descendants()
?
Here is another approach:
if (docToValidate.Root.Descendants().Any())
{
// has child elements.
{
else
{
// does not have any child elements.
}
where 'docToValidate' is of type of XDocument.
精彩评论