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

8
我正在尝试理解我在Linq to XML中遇到的问题,看起来应该很简单,但即使在浏览了这里关于Linq to XML的问题之后,我仍然无法完全理解它。

以以下XML为例:

<users>
    <user id="1">
        <contactDetails>
            <phone number="555 555 555" />
        </contactDetails>
    </user>
    <user id="2">
        <contactDetails />
    </user>
</users>

我现在想检查ID为2的用户是否有电话号码。有人能提供一个解决方案吗?就像我说的那样,这似乎应该很简单...谢谢,Ola
3个回答

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();

3

也许有更好、更流畅的方法来做这件事(我对Linq-to-XML还不是非常熟悉),但是这段代码应该可以工作:

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

foreach (XElement user in yourDoc.Descendants("user"))
{
    foreach(XElement contact in user.Descendants("contactDetails"))
    {
       var phone = contact.Descendants("phone");

       bool hasPhone = (phone.Count() > 0);
    }
}

它基本上枚举了XML中所有“user”节点,然后枚举了用户节点中的所有“contactDetails”节点,并检查其中是否有任何“phone”子节点。

.Descendants()调用将返回一个XElement节点列表,如果没有你查询的类型,则该列表(IEnumerable<T>)上的.Count()将返回0-这就是我的代码所检查的内容。

Marc


1

在Linq to xml中,您可以在获取值之前进行快速检查:

if (!xe.Root.Element("Date").IsEmpty)
{
    pd.datefield = System.Convert.ToString(xe.Root.Element("Date").Value);
}

由于不会创建带有空数据的标签,因此无法处理数据库中的NULL数据

为此,您需要循环遍历子元素


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接