Checking an XElement for Existence of One of Several Possible XElements
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/></co开发者_如何学Pythonlor>
Dim xe4 = <color><aqua/></color>
Dim xe5 = <color><green/></color>
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
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)?
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));
Even if the VB fights you, I'm sure you can use .Any
instead of .SingleOrDefault
and a null
check.
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>
or even as an attribute:
<somexml color="blue"/>
精彩评论