1

有没有办法确定 XElement 是否包含任何指定元素之一?例如,我有要检查的 XElements:

Dim xe1 = <color><blue/></color>
Dim xe2 = <color><red/></color>
Dim xe3 = <color><powderBlue/></color>
Dim xe4 = <color><aqua/></color>
Dim xe5 = <color><green/></color>

我希望能够查询任何 xelements 以查看它们是否包含元素或在它们之下,如果是则返回 true,否则返回 false <red/><green/><blue/>

我希望它会更简单,但我能想到的最好的是:

Dim primaryColor = From e In xe1.Elements Where e.Name = "blue" Or e.Name = "red" Or e.Name = "green"
Dim primaryColorTrue = primaryColor.SingleorDefault
If primaryColorTrue IsNot Nothing Then
'Blah
End If

有没有人有更好的方法来做到这一点,例如将那些红色/绿色/蓝色的 xelements 放入一个数组并使用 Elements.Contains(list of elements) 之类的东西?

4

1 回答 1

2

如果我理解正确 - 也许(使用 C#,抱歉 - 但这里没有真正的 C# 特定逻辑):

var colors = new[] {"red", "green","blue"};
bool any = el.Descendants().Any(child => colors.Contains(child.Name.LocalName));

即使 VB 和你打架,我相信你也可以用check来.Any代替。.SingleOrDefaultnull

对于信息,在这里使用元素对我来说听起来很奇怪。如果可能的话,我只是将颜色名称作为文本

<somexml><color>blue</color></somexml>

甚至作为一个属性:

<somexml color="blue"/>
于 2009-11-26T20:21:13.650 回答