user3553401 user3553401 - 1 month ago 33 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.


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.


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

Dim xml = <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)

Console Output :


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