简体   繁体   中英

Retrieving a sibling xml element

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?

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

In VB this would be

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

The C# version should be similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM