0

我想知道如何检查每个特定元素是否存在。
我编写了以下代码,但我认为这并不聪明。

if(xmlDoc.Descendants("ElementA").Any() && xmlDoc.Descendants("ElementB").Any() && ....
4

1 回答 1

2

你可以这样做:

if (new[] {"ElementA", "ElementB", "ElementC"}
           .All(element => xmlDoc.Descendants(element).Any()))
{
}

如果可以的话,我建议保存一个成员:

private static readonly string[] ELEMENTS = new string[]
                                                {
                                                    "ElementA",
                                                    "ElementB",
                                                    "ElementC"
                                                };

而不是每次都重新创建它。然后你可以这样做:

if (ELEMENTS.All(element => xmlDoc.Descendants(element).Any()))
{
}
于 2012-05-08T06:34:17.760 回答