user3553401 user3553401 - 4 days ago 6
Vb.net Question

Linq to XML VB.NET Select and edit rows and cells from a HTML table

I have a plain table made of rows (tr) and cells (td) with no specific attributes.

I can read it and parse it as xElement, then I need to use LINQ to XML and perform calculations and changes on some cells based on their position in the row.

<tr><td>A</td><td>12</td><td>2</td><td>Result</td></tr>
<tr><td>BA</td><td>3.65</td><td>6</td><td>Result</td></tr>


For instance I need to add the values of cells 2 and 3 an write the result into cell 4 for EACH row.

I can find plenty of examples where a given cell has a name attribute, bot none where I can select all rows and for each row apply a calculation on cells based on their relative position.

Answer

One possible way, assuming your table rows has consistent structure* :

Dim xml = <table>
              <tr><td>A</td><td>12</td><td>2</td><td>Result</td></tr>
              <tr><td>BA</td><td>3.65</td><td>6</td><td>Result</td></tr>
          </table>

'loop through table rows'
For Each row As XElement In xml.<tr>
    'sum value of 2nd & 3rd cells'
    Dim sum = row.<td>.Skip(1).Take(2).Sum(Function(x) CDec(x))
    'get the last cell where the sum result will be displayed'
    Dim result = row.<td>.Last()
    'update last cell with sum result'
    result.Value = sum.ToString(CultureInfo.InvariantCulture)
Next
Console.WriteLine(xml.ToString())

Console Output :

<table>
  <tr>
    <td>A</td>
    <td>12</td>
    <td>2</td>
    <td>14</td>
  </tr>
  <tr>
    <td>BA</td>
    <td>3.65</td>
    <td>6</td>
    <td>9.65</td>
  </tr>
</table>

* : every row has 4 cells, the 2nd & 3rd column always contain valid decimal string

Comments