2016-02-05 55 views
0

我使用Html-agility-Pack來解析HTML文本塊。是否有可能通過它們的屬性/屬性值來查找所有元素的列表?使用html-agility-pack查找包含數據 - 屬性的所有元素

舉一個例子,下面是一個html文本樣例。使用Html-agility-pack如何找到具有「data-glossaryid」屬性的所有元素?

<p> sample text <a href="" data-glossaryid="F776EB48BD"></a> 
<p><img alt="my pic" src="/~/media/Images/mypic.jpg" /></p> 
sample text 
<a href="" data-glossaryid="5D476EB49E"></a> 
<p> more sample text </p> 
<span data-glossaryid="F776EB49EF"> </span> 

回答

3
// the html block of text to parse 
var a = @"<p> sample text <a href="""" data-glossaryid=""F776EB48BD""></a> 
<p><img alt=""my pic"" src=""/~/media/Images/mypic.jpg"" /></p> 
sample text <a href="""" data-glossaryid=""5D476EB49E""></a> 
<p> more sample text </p> 
<span data-glossaryid=""F776EB49EF""> </span>"; 

// create an HtmlDocument 
var htmlDocument = new HtmlDocument(); 
htmlDocument.LoadHtml(a); 

// get all elements with the attr data-glossaryid and prints its values 
foreach (var item in htmlDocument.DocumentNode.SelectNodes("//*[@data-glossaryid]")) 
    Console.WriteLine(item.GetAttributeValue("data-glossaryid", "")); 
+0

有許多HTML解析庫,HtmlAgilityPack是好的,但是當文檔太長,它提升的問題。從那時起,我受到AngleSharp的尊重。 –

+0

謝謝。這樣可行 – suneeth

相關問題