0

I have a set of xml elements that are siblings

<z>1</z>
<b>1</b>
<w>1</w>
<n>1</n>
<e>1</e>
<v>1</v>

XElement y is currently pointing to Element e. I now want to look at Element b.

The code

var y = e.ElementsBeforeSelf("b");

does return a collection with just the element b.

Of course, now I need to return just the single element b. I am not always certain that Element b will be a fixed number of elements above e. I am missing something really obvious here because I have not been able with looking at a lot of good articles to figure this out.

Things I have tried:

var y = e.ElementsBeforeSelf().First().Element("b");
var y = e.ElementsBeforeSelf("b").Element("b");
var y = e.ElementsBeforeSelf().Single().Element("b");
var y = e.ElementsBeforeSelf().Single(x=>x.Name=="b").Element("b");

How do I select and return just the single element b, starting with element e?

Chuck Bland
  • 255
  • 1
  • 2
  • 13

2 Answers2

3
var y = e.ElementsBeforeSelf("b").First();
Magnetron
  • 7,495
  • 1
  • 25
  • 41
  • An exception of type 'System.InvalidOperationException' occurred in System.Core.dll but was not handled in user code. Additional information: Sequence contains no elements. Which strikes me a little weird, because without the First(), I do get a collection that contains b. I can do a foreach loop and print the Name and Value. – Chuck Bland Jun 08 '17 at 21:13
  • @ChuckBland - I'm sure your xml contains a namespace. You must take it into account. – Alexander Petrov Jun 09 '17 at 00:30
  • @Alexander Petrov - That is a reasonable thing to check but no, there is no ns use. The ElementsBeforeSelf is working. I do get a collection and I can foreach through it to print each name. The challenge seems to be how to select the one item I want from the collection. I have tried var y = e.ElementsBeforeSelf("qci").Single(x => (string)x.Name=="b"); but it's returning null, even though I know b is in the collection. – Chuck Bland Jun 09 '17 at 06:25
  • @ChuckBland - This is absolutely working solution if there is no namespace. – Alexander Petrov Jun 09 '17 at 10:50
  • @ChuckBland This solution should work. Post more of your code and the `using` statments you're using. Another thing, which version of .Net are you using? If you create a List of any type (and populate it), can you use the First() statement or it gives you the same error? – Magnetron Jun 09 '17 at 11:19
  • I am marking this as the answer because...... well, it is, plus a upvote for patience. Bottom line: I had a typo when I tried his answer. – Chuck Bland Jun 09 '17 at 16:42
0

In VB this would be

    'y has element e
    Dim b As XElement
    b = y.Parent.<b>.SingleOrDefault

The C# version should be similar.

dbasnett
  • 11,334
  • 2
  • 25
  • 33