2011-06-14 4 views
3

여기 HTML 스 니펫이 있는데 원하는 것은 텍스트 노드 만 가져 와서 반복하는 것입니다. Pls 알려주세요. 감사.HTMLAgilityPack 모든 텍스트 노드 만 반복합니다.

<div> 
    <div> 
     Select your Age: 
     <select> 
      <option>0 to 10</option> 
      <option>20 and above</option> 
     </select> 
    </div> 
    <div> 
     Help/Hints: 
     <ul> 
      <li>This is required field. 
      <li>Make sure select the right age. 
     </ul> 
     <a href="#">Learn More</a> 
    </div> 
</div> 

결과 :

  1. 당신의 나이를 선택 :
  2. 0 10
  3. (20)와
  4. 도움말/힌트 위 :
  5. 이것은 필수 항목입니다.
  6. 올바른 연령을 선택하십시오.

    HtmlDocument doc = new HtmlDocument(); 
        doc.Load(yourHtmlFile); 
    
        foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//text()[normalize-space(.) != '']")) 
        { 
         Console.WriteLine(node.InnerText.Trim()); 
        } 
    

    윌 출력이 :

  7. 이 같은 더 많은

답변

17

뭔가를 알아

Select your Age: 
0 to 10 
20 and above 
Help/Hints: 
This is required field. 
Make sure select the right age. 
Learn More 
+0

위대한 작품 ... 고마워. –

1

내가 Google 홈페이지에 @ 사이먼 Mourier의 답변을 테스트하고 CSS를 많이했고, Javascript가 있으므로 추가 필터를 추가하여 필터를 제거했습니다.

public string getBodyText(string html) 
    { 
     string str = ""; 

     HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
     doc.LoadHtml(html); 

     try 
     { 
      // Remove script & style nodes 
      doc.DocumentNode.Descendants().Where(n => n.Name == "script" || n.Name == "style").ToList().ForEach(n => n.Remove()); 

      // Simon Mourier's Answer 
      foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//text()[normalize-space(.) != '']")) 
      { 
       str += node.InnerText.Trim() + " "; 
      } 
     } 
     catch (Exception) 
     { 
     } 

     return str; 
    }