2012-08-28 3 views
1

다음 HTML에서는 table 요소를 구문 분석 할 수 있지만 th 요소는 건너 뛸 수 없습니다.HTML 민첩성 팩을 사용하여 구문 분석 테이블

나는 단지 td 요소를 얻을 싶어하지만 내가 사용하려고하면

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

을 ... 나는 예외를 얻을.

<table class="tab03"> 
    <tbody> 
    <tr> 
     <th class="right" rowspan="2">first</th> 
    </tr> 
    <tr> 
     <th class="right">lp</th> 
     <th class="right">name</th> 
    </tr> 
    <tr> 
     <td class="right">1</td> 
     <td class="left">house</td> 
    </tr> 
    <tr> 
     <th class="right" rowspan="2">Second</th> 
    </tr> 
    <tr> 
     <td class="right">2</td> 
     <td class="left">door</td> 
    </tr> 
    </tbody> 
</table> 

내 코드 :

var document = doc.DocumentNode.SelectNodes("//table"); 
string store = ""; 

if (document != null) 
{ 
    foreach (HtmlNode table in document) 
    { 
     if (table != null) 
     { 
      foreach (HtmlNode row in table.SelectNodes("tr")) 
      { 
       store = ""; 
       foreach (HtmlNode cell in row.SelectNodes("th|td")) 
       { 
        store = store + cell.InnerText+"|"; 
       } 

       sw.Write(store); 
       sw.WriteLine(); 
      } 
     } 
    } 
} 

sw.Flush(); 
sw.Close(); 
+2

예외는 무엇입니까? –

답변

3

이 메서드는 LINQ를 사용하여 tdHtmlNode 인스턴스를 쿼리합니다.

출력이 val|val| (후행 파이프 포함)으로 나타났습니다.이 샘플은 val|val을 제거하는 덜 위험한 방법으로 string.Join(pipe, array)을 사용합니다.

using System.Linq; 

// ... 

var tablecollection = doc.DocumentNode.SelectNodes("//table"); 
string store = string.Empty; 

if (tablecollection != null) 
{ 
    foreach (HtmlNode table in tablecollection) 
    { 
     // For all rows with at least one child with the 'td' tag. 
     foreach (HtmlNode row in table.DescendantNodes() 
      .Where(desc => 
       desc.Name.Equals("tr", StringComparison.OrdinalIgnoreCase) && 
       desc.DescendantNodes().Any(child => child.Name.Equals("td", 
        StringComparison.OrdinalIgnoreCase)))) 
     { 
      // Combine the child 'td' elements into an array, join with the pipe 
      // to create the output in 'val|val|val' format. 
      store = string.Join("|", row.DescendantNodes().Where(desc => 
       desc.Name.Equals("td", StringComparison.OrdinalIgnoreCase)) 
       .Select(desc => desc.InnerText)); 

      // You can probably get rid of the 'store' variable as it's 
      // no longer necessary to store the value of the table's 
      // cells over the iteration. 
      sw.Write(store); 
      sw.WriteLine(); 
     } 
    } 
} 

sw.Flush(); 
sw.Close(); 
3

귀하의 XPath 구문이 올바르지 않습니다. 시도하십시오 :

HtmlNode cell in row.SelectNodes("//td") 

이 당신에게 foreach으로 반복 될 수 td 요소의 컬렉션을 얻을 것이다.

+0

이 제안으로 나는 1 | house | 2 | door를 얻었지만 다음 td로 볼드체를 얻고 싶다. – Wojciech

관련 문제