2016-10-08 4 views
2

にテーブルを解析だから私はこのようにHTMLを持っている:Htmlの敏捷性パックオブジェクト

<tr class="row1"> 
     <td class="id">123</td> 
     <td class="date">2014-08-08</td> 
     <td class="time">12:31:25</td> 
     <td class="notes">something here</td> 
</tr> 
<tr class="row0"> 
     <td class="id">432</td> 
     <td class="date">2015-02-09</td> 
     <td class="time">12:22:21</td> 
     <td class="notes">something here</td> 
</tr> 

そしてそれは、各顧客の行のためのそのように続けます。私はオブジェクトに各テーブル行の内容を解析したい。私はいくつかの方法を試しましたが、正しく動作させることができません。

これは、私はそれはそれは、各ループ上の表の最後の行の情報を出力することをポイントに働き、現在

HtmlDocument doc = new HtmlDocument(); 
doc.LoadHtml(html); 
foreach (HtmlNode row in doc.DocumentNode.SelectNodes("//table[@id='customerlist']//tr")) 
{ 
    Customer cust = new Customer(); 
    foreach (HtmlNode info in row.SelectNodes("//td")) 
    { 
     if (info.GetAttributeValue("class", String.Empty) == "id") 
     { 
      cust.ID = info.InnerText; 
     } 
     if (info.GetAttributeValue("class", String.Empty) == "date") 
     { 
      cust.DateAdded = info.InnerText; 
     } 
     if (info.GetAttributeValue("class", String.Empty) == "time") 
     { 
      cust.TimeAdded = info.InnerText; 
     } 
     if (info.GetAttributeValue("class", String.Empty) == "notes") 
     { 
      cust.Notes = info.InnerText; 
     } 
    } 
    Console.WriteLine(cust.ID + " " + cust.TimeAdded + " " + cust.DateAdded + " " + cust.Notes); 
} 

持っているものです。私は何か非常に単純なものを見逃していますが、何が見えないのですか。

また、オブジェクトをうまく作成するための私の方法ですか、またはコンストラクタを使用して変数からオブジェクトを作成する必要がありますか?例えば。

string Notes = String.Empty; 
if (info.GetAttributeValue("class", String.Empty) == "notes") 
{ 
    Notes = info.InnerText; 
} 
.. 
Customer cust = new Customer(id, other_variables, Notes, etc); 

答えて

1

XPathクエリが間違っています。あなたはtdの代わり//tdを使用する必要があります。SelectNodes()//tdを渡す

foreach (HtmlNode info in row.SelectNodes("td")) 

は、ドキュメント内のすべて<td>の要素にマッチします、したがって、あなたの内側のループが8回の代わりに4回、そして最後の4回、常に上書きを実行しますCustomerオブジェクトで以前に設定された値。

XPath Examples

関連する問題