2017-01-03 4 views
0

これはわかりません。XPath、HTML内の複数のノードから複数の要素を選択

"item extend featured"の値を持つクラス(以下のコード)を持つすべてのノードを検索する必要があります。これらのクラスでは、<h2 class="itemtitle">hrefという値のすべてのInnerTextと、<div class="title-additional">のすべてのInnerTextを選択する必要があります。

<li class="item extend featured"> 
    <div class="title-box"> 
     <h2 class="itemtitle"> 
      <a target="_top" href="www.example.com/example1/example2/exammple4/example4" title="PC Number 1">PC Number 1</a> 
     </h2> 
     <div class="title-additional"> 
      <div class="title-km">150 km</div> 
      <div class="title-year">2009</div> 
      <div class="title-price">250 €</div> 
     </div> 

出力はこのようなものでなければなりません:だから

Title: 
href: 
Title-km: 
Title-year: 
Title-Price: 
-------------- 


Title: 
href: 
Title-km: 
Title-year: 
Title-Price: 
-------------- 

、問題は、HTML内のすべての"item extend featured"ノードを横断し、私は、各ノードから上記必要な項目を選択する方法、ありますか?私が理解したよう

、このような何かが動作するはずですが、それは途中

EDITを壊す:私は気づいた、そこにまったく同じクラスを共有するサイト上の広告があり、彼らは明らかに私は必要な要素を持っていません。考えなければならない多くの問題。 (あなたはおそらく連合を使用しない限り)あなたは1つのクエリを使用して異なるレベルで複数の結果を返すことができないとして、あなたが達成しようとしている何

var items1 = htmlDoc.DocumentNode.SelectNodes("//*[@class='item extend featured']"); 

foreach (var e in items1) 
{ 
    var test = e.SelectSingleNode(".//a[@target='_top']").InnerText; 
    Console.WriteLine(test); 
} 
+0

をテストしていない質問を追加しました。 – CsharpNoob

+0

これまでに試したコードを共有できますか? – eLRuLL

+0

答えを更新してください。これは読めません。 – eLRuLL

答えて

1
var page = new HtmlDocument(); 
page.Load(path); 
var lists = page.DocumentNode.SelectNodes("//li[@class='item extend featured']"); 
foreach(var list in lists) 
{ 
    var link = list.SelectSingleNode(".//*[@class='itemtitle']/a"); 
    string title = link.GetAttributeValue("title", string.Empty); 
    string href = link.GetAttributeValue("href", string.Empty); 
    string km = list.SelectSingleNode(".//*[@class='title-km']").InnerText; 
    string year = list.SelectSingleNode(".//*[@class='title-year']").InnerText; 
    string price = list.SelectSingleNode(".//*[@class='title-price']").InnerText; 
    Console.WriteLine("Title: %s\r\n href: %s\r\n Title-km: %s\r\n Title-year: %s\r\n Title-Price: %s\r\n\r\n", title, href, km, year, price); 
} 
+0

これは基本的には、ありがとうTONです。 – CsharpNoob

1

は、複数のXPath式が必要です。あなたが探しているかもしれない何

は、これに似たものである:

var listItems = htmlDoc.DocumentNode.SelectNodes("//li[@class='item extend featured']"); 

foreach(var li in listItems) { 
    var title = li.SelectNodes("//h2/a/text()"); 
    var href = li.SelectNodes("//h2/a/@href"); 
    var title_km = li.SelectNodes("//div[@class='title-additional']/div[@class='title-km']/text()"); 
    var title_... // other divs 
} 

注:コード

関連する問題