2014-10-06 67 views
1

我已經從我的SharePoint網站加載了一個Xelement。vb.net:從Xelement獲取數據<table></table>

Dim elTable2 As XElement = <table border="1" id="table2" style="font-size:1em;border-collapse:collapse;display:inline;width:100%"> 
<tbody> 
    <tr class="ms-rteTableHeaderRow-default" style="text-align:center"> 
     <th class="ms-rteTableHeaderFirstCol-default">​</th> 
     <th class="ms-rteTableHeaderOddCol-default">LAN IP​</th> 
     <th class="ms-rteTableHeaderEvenCol-default">Username​</th> 
     <th class="ms-rteTableHeaderOddCol-default">Password​</th> 
     <th class="ms-rteTableHeaderEvenCol-default">Port​</th> 
     <th class="ms-rteTableHeaderOddCol-default">OS​</th> 
     <th class="ms-rteTableHeaderEvenCol-default">Extra Info​</th> 
    </tr> 
    <tr class="ms-rteTableOddRow-default" style="text-align:center"> 
     <th class="ms-rteTableFirstCol-default">Netasq</th> 
     <td class="ms-rteTableOddCol-default"></td> 
     <td class="ms-rteTableEvenCol-default"></td> 
     <td class="ms-rteTableOddCol-default">​</td> 
     <td class="ms-rteTableEvenCol-default">​</td> 
     <td class="ms-rteTableOddCol-default">​</td> 
     <td class="ms-rteTableEvenCol-default">​</td> 
    </tr> 
    </tbody> 
</table> 

表中將有未知數量的行。我可以循環查看所有行並檢查第一列中的數據嗎?

回答

0

您可以利用Html Agility Pack達到此目的。它是一個.NET代碼庫,允許解析HTML內容並支持普通XPATH或XSLT。

Dim table As XElement = <table border="1" id="table2" style="font-size:1em;border-collapse:collapse;display:inline;width:100%"> 
           <tbody> 
            <tr class="ms-rteTableHeaderRow-default" style="text-align:center"> 
             <th class="ms-rteTableHeaderFirstCol-default">​Val</th> 
             <th class="ms-rteTableHeaderOddCol-default">LAN IP​</th> 
             <th class="ms-rteTableHeaderEvenCol-default">Username​</th> 
             <th class="ms-rteTableHeaderOddCol-default">Password​</th> 
             <th class="ms-rteTableHeaderEvenCol-default">Port​</th> 
             <th class="ms-rteTableHeaderOddCol-default">OS​</th> 
             <th class="ms-rteTableHeaderEvenCol-default">Extra Info​</th> 
            </tr> 
            <tr class="ms-rteTableOddRow-default" style="text-align:center"> 
             <td class="ms-rteTableFirstCol-default">Netasq</td> 
             <td class="ms-rteTableOddCol-default"></td> 
             <td class="ms-rteTableEvenCol-default"></td> 
             <td class="ms-rteTableOddCol-default">​</td> 
             <td class="ms-rteTableEvenCol-default">​</td> 
             <td class="ms-rteTableOddCol-default">​</td> 
             <td class="ms-rteTableEvenCol-default">​</td> 
            </tr> 
           </tbody> 
          </table> 


    Dim html = New HtmlDocument() 
    html.LoadHtml(table.ToString()) 
    For Each row In html.DocumentNode.SelectNodes("//tr[position()>1]") 'XPath expression to select table rows and skip table header 

     Dim cell As HtmlNode = row.SelectSingleNode("td[1]") 'Get cell for first column 
     Console.WriteLine(cell.InnerText) 
    Next