1

I'm trying to process some XML with LINQ (vb.net) to return all rows between two specific rows:

XML:

<ss:Table>
   <ss:Row ss:FirstRow="true">...</ss:Row>
   <ss:Row>1</ss:Row>
   <ss:Row>2</ss:Row>
   <ss:Row>3</ss:Row>
   <ss:Row ss:LastRow="true">...</ss:Row>
</ss:Table>

I can grab the starting row using the following:

Dim Rows = From item In dg...<Table>...<Row> Select item Where item.@ss:FirstRow = "true"

But I bet there is a LINQ elegant way of getting rows with (1,2,3). Obviously I can't find it or I wouldn't be asking here. Thanks!

WhiskerBiscuit
  • 4,795
  • 8
  • 62
  • 100

1 Answers1

0

I think you are after the two functions ElementsAfterSelf and TakeWhile to do the trick. Apologies that my answer is in C#.

var xml = @"
<Table>
    <Row FirstRow='true'>bob</Row>
    <Row>1</Row>
    <Row>2</Row>
    <Row>3</Row>
    <Row LastRow='true'>bob</Row>
    <Row FirstRow='true'>mary</Row>
    <Row>4</Row>
    <Row>5</Row>
    <Row>6</Row>
    <Row LastRow='true'>mary</Row>
    <Row FirstRow='true'>jane</Row>
    <Row>7</Row>
    <Row>8</Row>
    <Row>9</Row>
    <Row LastRow='true'>jane</Row>
</Table>";

var doc = XDocument.Parse(xml);
var rows = (from row in doc.Root.Elements("Row")
            where row.Attribute("FirstRow") != null
            select new
            {
                Name = row.Value,
                Values = row.ElementsAfterSelf().TakeWhile(n => n.Attribute("LastRow") == null).ToList()
            }).ToList();

rows.Dump();

I used LinqPad to put together the answer hence the Dump method call at the end to see the output of the operation.

atom.gregg
  • 987
  • 8
  • 14