2012-05-22 2 views
3

이것은 내 샘플 페이지입니다. 나는 하나의 문자열에 태그의 모든 내부 텍스트를 가져오고 싶다. 나는 그렇게이 코드를 사용하지만 제대로 작동하지 않습니다 그 코드를 작성하지만 내가 하나의 문자열로 모든 태그의 내부 텍스트를 얻으려면여러 <a> 태그의 Innertexts를 얻는 방법?

<body> 
    <div id="infor"> 
     <div id="genres"> 
      <a href="#" >Animation</a> 
      <a href="#" >Short</a> 
      <a href="#" >Action</a> 
     </div> 
    </div> 
</body> 

제대로 작동하지 않습니다.

Animation, Animation, Animation, 

하지만이 같은 출력이 원하는 : (반환 값)

class Values 
{ 
    private HtmlAgilityPack.HtmlDocument _markup; 

    HtmlWeb web = new HtmlWeb(); //creating object of HtmlWeb 
    form1 frm = new form1; 

    _markup = web.Load("mypage.html"); // load page 

    public string Genres 
    { 
     get 
     { 
      HtmlNodeCollection headers = _markup.DocumentNode.SelectNodes("//div[contains(@id, 'infor')]/a"); // I filter all of <a> tags in <div id="infor"> 
      if (headers != null) 
      { 
       string genres = ""; 
       foreach (HtmlNode header in headers) // I'm not sure what happens here. 
       { 
        HtmlNode genre = header.ParentNode.SelectSingleNode(".//a[contains(@href, '#')]"); //I think an error occurred in here... 
        if (genre != null) 
        { 
         genres += genre.InnerText + ", "; 
        } 
       } 
       return genres; 
      } 
      return String.Empty; 
     } 
    } 

    frm.text1.text=Genres; 
} 

텍스트 1은 문제가 header.ParentNode.SelectSingleNode(".//a[contains(@href, '#')]") 문처럼

Animation, Short, Action, 
+0

은 실제로 'InnerText'를 (를) 가져 오려는 노드가 아닌 'header'입니다. 장르 선택 코드는 마치 매번 분명히 똑같은 형제 자매를 얻는다고 말하는 것처럼 보입니다 ... 그 코드로 무엇을하려고합니까? – Chris

답변

1

약간 Linq에와 후손을 사용하는 것은 거기 쉽게 얻을 것이다, 나는 생각 : 당신은 그냥 같은 하나의 그 첫 번째 장소에서 그것을 좁혀 선택 할 수있는 경우 그러나, 두 번째 선택하고을 할 바보 .

var genreNode = _markup.DocumentNode.Descendants("div").Where(n => n.Id.Equals("genre")).FirstOrDefault(); 
if (genreNode != null) 
{ 
    // this pulls all <a> nodes under the genre div and pops their inner text into an array 
    // then joins that array using the ", " as separator. 
    return string.Join(", ", genreNode.Descendants("a") 
     .Where(n => n.GetAttributeValue("href", string.Empty).Equals("#")) 
     .Select(n => n.InnerText).ToArray()); 
} 
1

것 같습니다. 상위 div 요소로 돌아가서 조건과 일치하는 첫 번째 a 요소를 찾습니다 (항상 같은 것임). 이미 a 노드가 있으므로 다른 선택을 수행하는 대신 속성을 통해 속성을 확인할 수 있습니다.

HtmlNodeCollection headers = _markup.DocumentNode.SelectNodes("//div[contains(@id, 'infor')]/a[contains(@href, '#')]"); 
if (headers != null) 
    { 
    string genres = ""; 
    foreach (HtmlNode header in headers) // i not sure what happens here. 
     { 
     genres += header.InnerText + ", "; 
     } 
    return genres; 
    } 
관련 문제