I have the below markup, in which each item
element must contain exactly one a
, b
, c
, or d
element, and in addition can contain a variety of additional elements. The position of the required (a
, b
... type) elements is not certain.
<root>
<item>
<a>...</a>
...
<item>
<item>
...
<d>...</d>
<item>
<item>
<c>...</c>
<item>
...
</root>
Using XDocument, how can I express the following:
Return the first child element of type
a
,b
,c
, ord
.
I'm currently using a chain of if-else statements, but this blasphemy must go; it seems way too much for such a seemingly easy task:
foreach (XElement xItem in xmlDoc.Root.Elements("item"))
{
if (xItem.Element("a") != null)
{
// element <a>...</a> found
}
else if (xItem.Element("b") != null)
{
// element <b>...</b> found
}
...
}
Well it sounds like you might want something like:
var names = new XName[] { "a", "b", "c", "d" };
var element = xmlDoc.Root
.Elements("item")
.Elements()
.FirstOrDefault(x => names.Contains(x.Name));
See more on this question at Stackoverflow