Checking an XElement for Existence of One of Sever

2019-06-04 00:23发布

问题:

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>

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)?

回答1:

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"/>