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

发布于 2024-10-08 05:57:05 字数 409 浏览 0 评论 0原文

这是我的方法:

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

当它位于“文档”变量中时,此代码会中断:

<ipb></ipb>

既然它没有后代,为什么它要输入 IF 条件?它不应该尝试加载任何东西,但它会加载任何东西,并且当它发现没有东西可以刮擦时就会中断。

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

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 code 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

嘿看小鸭子会跑 2024-10-15 05:57:05

您是否尝试过使用:

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

Root 元素位于 XDocument 下方。

Have you tried using:

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

The Root element sits below the XDocument.

波浪屿的海角声 2024-10-15 05:57:05

ipb 是该文档的第一个后代,对吧?您不需要 document.Root.Descendants() 吗?

ipb is your first descendant on the document, right? Don't you want document.Root.Descendants() ?

比忠 2024-10-15 05:57:05

这是另一种方法:

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

其中“docToValidate”是 XDocument 类型。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文