为什么是XDocument.Descendants()。Count()> 0表示空文档?

时间:2010-12-21 02:03:39

标签: c# linq-to-xml

这是我的方法:

var document = XDocument.Parse(source);
if (document.Descendants().Count() > 0)
{
    // Some code that shouldn't execute
}
else
{
    // Code that should execute
}

此代码在'document'变量中时会中断:

<ipb></ipb>

由于这不具有后代,为什么它进入IF条件?不应该尝试加载任何东西,但是当它找不到任何东西时它会发生并且会中断。

使用断点我可以确认文档变量具有我在上面发布的内容,并且它确实输入了if。

3 个答案:

答案 0 :(得分:5)

您是否尝试过使用:

document.Root.Descendants().Count() > 0;

Root元素位于XDocument下面。

答案 1 :(得分:1)

ipb是你文件的第一个后代,对吗?你不想要document.Root.Descendants()吗?

答案 2 :(得分:0)

这是另一种方法:

if (docToValidate.Root.Descendants().Any())
{
   // has child elements.
{
else
{
   // does not have any child elements.
}

其中&#39; docToValidate&#39;是XDocument的类型。