簡體   English   中英

如何在C#的html文件中指定第二個表

[英]How to specify the second table in an html file for C#

我需要獲取第二張表的第四行的總和。 我想從第二列開始進行總結。 我該怎么做呢?

    static void Main()
    {
        String htmlFile = "C:/Temp/Test_11.html";

        HtmlDocument doc = new HtmlDocument();
        doc.Load(htmlFile);

        //var sum = doc.DocumentNode.SelectSingleNode("//table")  // <<<< No error when I access the first table 
        var sum = doc.DocumentNode.SelectSingleNode("//table[2]")  // <<<< Error when I try to access the 2nd table
            .Elements("tr")
            // Skip this many rows from the top
            .Skip(1)
            // .ElementAt(2) = third column
            .Sum(tr => int.Parse(tr.Elements("td").ElementAt(2).InnerText));
        Console.WriteLine(sum);

        Console.ReadLine();
    }

以下是由兩個表組成的html文件。 總和的結果應為26。

<html>
<head>
<title>Tables</title>
</head>
<body>
<table border="1">
  <tr>
    <th>Environment1</th>
    <th>Databases</th>
    <th>Sites</th>
    <th>Site Collection Storage Used (GB)</th>
    <th>Ref</th>
</th>
  </tr>
  <tr>
    <td>Public1</td>
    <td>14</td>
    <td>28</td>
    <td>32.6602</td>
    <td>2</td>
  </tr>
  <tr>
    <td>Local1</td>
    <td>4</td>
    <td>9</td>
    <td>21.0506</td>
    <td>1</td>
  </tr>
  <tr>
    <td>Shared1</td>
    <td>6</td>
    <td>9</td>
    <td>17.092</td>
    <td>9</td>
  </tr>
</table>
<p></p>
<table border="1">
  <tr>
    <th>Environment2</th>
    <th>Databases</th>
    <th>Sites</th>
    <th>Site Collection Storage Used (GB)</th>
    <th>Ref</th>
 </th>
  </tr>
  <tr>
    <td>Public2</td>
    <td>15</td>
    <td>13</td>
    <td>31.5602</td>
    <td>1</td>
  </tr>
  <tr>
    <td>Local2</td>
    <td>5</td>
    <td>8</td>
    <td>7.0302</td>
    <td>3</td>
  </tr>
  <tr>
    <td>Shared2</td>
    <td>4</td>
    <td>5</td>
    <td>13.109</td>
    <td>4</td>
  </tr>
</table>

</body>
</html>

請在這件事上給予我幫助

以下示例執行相同的操作,唯一的問題是我已經對xPath中的位置和元素進行了硬編碼,您可以自由更改它們以適應您的需求。

var tbl = xdoc.SelectNodes("//table[2]//tr[4]//td[position()>1]");

// In order to select the 1st table, the following statement can be used.
//var tbl = xdoc.SelectNodes("//table[2]//tr[4]//td[position()>1]");

int sum = 0;

foreach (XmlNode item in tbl) 
{
     decimal value = 0;
     if (decimal.TryParse(item.InnerText, out value))
     {
         sum += (int)value;
     }
 }

 Console.WriteLine("Number of (Web Application) sites: " + sum);

有幾點要注意。 您的值以十進制表示,並且已將它們視為整數。 因此,我使用了十進制臨時變量來獲取所有值,然后進行整數轉換。 但是,這不是最佳實踐。 您必須根據您的確切要求進行調查。

此外,我使用了TryParse以便僅可以解析的項目可以用於計算。

請在這里分享您的理解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM