views:

178

answers:

1

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

+2  A: 

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"/>
Marc Gravell
Funny stuff- I didn't like your original answer, so I coded up a solution I thought was better, refreshed the page, and you had the same solution as me! So +1.
RichardOD
Worked like a charm, thank you! Here it is in VB - Dim colors() = New String() {"green", "blue", "red"} Dim any As Boolean = el.Descendants.Any(Function(e) colors.Contains(e.Name.LocalName))
Otaku
Yeah, the thing-a-muh-jig with using elements was just a sample of querying for children elements that may or may not exist. The XML files are not mine, so I can't change those.
Otaku