user1741874
user1741874

Reputation:

Selecting nth child element based on parent elements attribute

I'm running into a bit of a problem using Linq to XML to query this not-so-hot xml document.

An example of the schema is like so.

<Data>
    <Row Oper="" Val="THIS">
       <Col Oper="" Val="">
           <Out Val="0"/>
           <Out Val=""/>
           <Out Val="16600"/>
           <Out Val="10000"/>
       </Col>
    </Row>
    <Row Oper="" Val="THAT">
        <Out Val=...">
        ....
    </Row>
</Data>

Basically; I need to match the main element based on Row Val and then get nth "Val" based on an arbitrary number.

To clarify; I have to match on "This" and get the third child of row. How would I go about that?

Expected Output: "16600"

Here's what I'm looking at (and I don't know how to select nth children in linq)

var query = (from nt in ntd.Descendants("Data").Elements("Out").Skip(1)
             where nt.Element.Attribute("Val").Value == "this"
             select nt.[nth child of row somehow].Attribute("Val").Value)

Just to be clear: I'm not allowed to change the XML document structure.

Upvotes: 2

Views: 1386

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

.ElementAt(3) .ElementAt(2) gives you third element from collection - it's 0-based index ...

Your sample XML does not totally match the query you've shown, so I decided to follow the schema, not the query:

var query = from r in ntd.Root.Elements("Row")
            where (string)r.Attribute("Val") == "THIS"
            select (string)r.Element("Col").Elements("Out").ElementAt(2).Attribute("Val")

Upvotes: 3

Related Questions