检查XElement是否存在多个可能的XElement之一 [英] Checking an XElement for Existence of One of Several Possible XElements
问题描述
是否可以确定XElement是否包含任何指定的元素之一?例如,我有要检查的XElement:
Is there a way to determine if an XElement contains one of any specified elements? For example, I have XElements that I'll want to check:
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,以查看它们是否包含它们下面的元素<red/>
,<green/>
或<blue/>
,如果是,则返回true,否则返回false.
I'd like to be able to query any of the xelements to see if they containt the elements <red/>
, <green/>
or <blue/>
below them and return true if so, false if not.
我希望这会更简单,但是我能想到的最好的方法是:
I was hoping that it would be simplier, but the best I could come up with was:
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(元素列表)之类的东西?
Does anyone have a better way to do this, such as putting those xelements of red/green/blue into an array and using something like Elements.Contains(list of elements)?
推荐答案
如果我正确理解-也许(使用C#,对不起-但此处没有真正的C#特定逻辑):
If I understand correctly - perhaps (using C#, sorry - but no real C# specific logic here):
var colors = new[] {"red", "green","blue"};
bool any = el.Descendants().Any(child => colors.Contains(child.Name.LocalName));
即使VB与您抗争,我敢肯定您可以使用.Any
代替.SingleOrDefault
和null
支票.
Even if the VB fights you, I'm sure you can use .Any
instead of .SingleOrDefault
and a null
check.
有关信息,在这里使用元素听起来很奇怪;如果可能的话,我只是将颜色名称作为 text :
For info, using elements here to me sounds like an odd idea; I'd just have the color name as the text if possible:
<somexml><color>blue</color></somexml>
或什至作为属性:
<somexml color="blue"/>
这篇关于检查XElement是否存在多个可能的XElement之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!