2011-08-08 12 views
0

div間でデータを抽出しようとしています。私はリンクをしたい場合HtmlAgilityの問題

<div class="movie_general"><div class="img"><a href="/Movies.html" title="Watch Movie"> 

フォアの例では、 "/Movies.htmlは、" 私は使用:

string hrefValue = doc.DocumentNode 
      .Descendants("div") 
      .Where(x => x.Attributes["class"].Value == "movie_general") 
      .Select(x => x.Element("a").Attributes["href"].Value) 
      .FirstOrDefault(); 

      MessageBox.Show(hrefValue); 

しかし、私はどこに(X => x.Attributes [ "クラス"]でとNullReferenceExceptionを取得します。値== "movie_general")

私は間違っていますか?

答えて

1

これは、Linqプロバイダがドキュメント内の他のすべてのノードを反復して検索に一致するかどうかをチェックする必要があるためです。このドキュメントにはclass属性を持たない少なくとも1つのdivが必要です。したがって、存在しない属性の属性Valueを読み取ろうとすると、エラーが発生します。

すでにクラスを知っているなら、この

.Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "movie_general") 
.Select(x => x.Element("a") != null && x.Element("a").Attributes["href"] != null ? x.Element("a").Attributes["href"].Value : string.Empty) 
+0

今はnull例外。要素( "a")。属性["href"]。値)lol – zenpark

+0

ここでもヌルチェックを行う必要がありますか? – zenpark

+0

はい、する必要があります。それは同じ問題です。内部に 'a'ノードがない場合、別のNullReferenceExceptionが発生します。 – Doug

0

この

.Where(x => x.Attributes["class"].Value == "movie_general") 
.Select(x => x.Element("a").Attributes["href"].Value) 

を交換し、タグはそれに従属することを、なぜちょうど直接使用してそれをつかむません:

HtmlDocument doc = new HtmlDocument(); 
    doc.Load("C:\\temp\\stackhtml.html"); 
    string link = doc.DocumentNode.SelectSingleNode("//div[@class='movie_general']//a").GetAttributeValue("href", "unkown"); 
    Console.WriteLine(link); 
    Console.ReadLine(); 

と結果:

enter image description here

私はそれをこすりことができるように、あなたの例にdivタグを閉じる追加され、私のCドライブ上のファイルにダンプ:.Select(x => xで

<div class="movie_general"> 
    <div class="img"> 
     <a href="/Movies.html" title="Watch Movie"> 
    </div> 
</div> 
関連する問題