2016-07-08 51 views
2

簡介:分組結果的XPath

假設我們有這樣的HTML代碼:

<div class="search-result">    
    <h2>TV-Series</h2> 
     <ul> 

      <li> 
    <div class="title"> 
     <a href="/subtitles/prison-break-sequel-first-season">Prison Break : Sequel - First Season</a>    
    </div>   
    <span class="subtle count">10 subtitles</span> 
      </li> 

      <li>    
    <div class="title"> 
     <a href="/subtitles/prison-break-fourth-season">Prison Break - Fourth Season</a>    
    </div>   
    <span class="subtle count">1232 subtitles</span> 
      </li> 

     </ul> 

    <h2>Popular</h2> 
     <ul> 

      <li> 
    <div class="title"> 
     <a href="/subtitles/prison-break-fourth-season">Prison Break - Fourth Season (2008)</a> 
    </div> 
    <div class="subtle count"> 
     1232 subtitles 
    </div> 

      </li> 

      <li> 
    <div class="title"> 
     <a href="/subtitles/prison-break-third-season">Prison Break - Third Season (2007)</a> 
    </div> 
    <div class="subtle count"> 
     644 subtitles 
    </div> 
      </li> 

     </ul> 

</div> 

的頁面是這樣的:

Sample Image

你可以在這裏看到原始網站:SubScene

我正在寫一個C#桌面應用程序,獲取本網站的信息。

在我學習HTML敏捷包之前,我使用了正則表達式。

使用此模式:<h2>[\s\S]+?</ul>我分開系列(如電視系列,熱門和...)。

然後在Rgular上使用此模式表達式:<li>[\s\S]+?<a href="(.+)">(.+)</a>[\s\S]+?class="subtle count"[\s\S]+?(\d*)[\s\S]+?</li>我從本站點獲取分類信息。

使用MatchCollection &使用組(與括號有所不同),我的方法在正則表達式中,返回我每個系列的二維列表,每行是關於一個電影和列包括:電影名稱,字幕數和字幕數下載鏈接。

和二維列表變得像一個數據庫財產以後這樣的: enter image description here

現在我瞭解到HTML敏捷性包

問:

我如何在HTML敏捷性包使用XPath創建這樣一個該名單?

2-我可以像之前看到的那樣使用哪個XPath創建像Regex這樣的組?

非常感謝。

+4

使用XSLT或XQuery或LINQ(您可以使用HTMLAgilityPack)更好地完成分組。如何顯示一些代碼,您必須解釋所需輸出的數據結構而不是顯示圖像?請參閱https://code.msdn.microsoft.com/LINQ-to-DataSets-Grouping-c62703ea以使用LINQ對示例進行分組。 –

+2

我只想分組像正則表達式的XPath ... – Parsa

回答

1

Martin Honnen的評論是正確的,沒有太多功能可以通過XPath提供'分組'。但是,可以使用循環並在一組元素上運行一組XPath來提取所需的數據。

首先,您提取每個標題元素,然後從標題中提取每個列表項,然後運行一個文件XPath以從每個文件中提取所需的值。

注意:此代碼是使用XPath針對XDocument而不是使用HTML Agility Pack編寫的,但XPath應該是相同的,無論如何。

var titleNodes = d.XPathSelectElements("/div[@class='search-result']/h2"); 
foreach (var titleNode in titleNodes) 
{ 
    string title = titleNode.Value.Dump(); 
    var listItems = titleNode.XPathSelectElements("following-sibling::ul[1]/li"); 

    foreach (var listItem in listItems) 
    { 
     var itemData = listItem.XPathEvaluate("div[@class='title']/a/text() | *[@class='subtle count']/text()"); 
    } 
} 

注中最後一個表達式中使用XPath |運營商在一個單一的XPath調用選擇多個不同孩子的價值觀。這些值是像你想要的那樣「分組」的。