检查Linq to XML是否存在XML子元素

Ola*_*son 8 xml linq linq-to-xml

我正试图解决我在Linq中遇到的问题,看起来应该很简单,但即使在这里浏览Linq to XML问题之后,我也无法理解它.

采取以下XML的内容:

<users>
    <user id="1">
        <contactDetails>
            <phone number="555 555 555" />
        </contactDetails>
    </user>
    <user id="2">
        <contactDetails />
    </user>
</users>
Run Code Online (Sandbox Code Playgroud)

我现在想检查ID为2的用户是否有电话号码.

有人建议一个解决方案,正如我所说,似乎应该很简单......

干杯,奥拉

dah*_*byk 13

这是一种查询方法:

XElement yourDoc = XElement.Load("your file name.xml");

bool hasPhone = (
    from user in yourDoc.Descendants("user")
    where (int)user.Attribute("id") == 2
    select user.Descendants("phone").Any()
    ).Single();
Run Code Online (Sandbox Code Playgroud)