2009-12-14 73 views
8

我问了in a codeplex discussion这个问题,但我希望在这里获得更快速的答案。HTML Agility Pack - 在特定节点之后选择节点

因此,我使用HTML敏捷包进行HTML解析在C#中。 我有以下HTML结构:

<body> 
    <p class="paragraph">text</p> 
    <p class="paragraph">text</p> 
    <p class="specific">text</p> 
    <p class="paragraph">text</p> 
    <p class="paragraph">text</p> 
</body> 

,我需要得到具有类“段落”带班“具体”的p元素之后存在的所有p元素。

有没有办法做到这一点?

谢谢。

回答

6

(如果那不存在的,任何的替代品为宜)

使用SkipWhile

例如在LINQPad5,6,7来自:

int[] a = { 6, 5, 6 ,7 }; 
a.SkipWhile(x=>x!=6).Skip(1).Dump(); 

所以根据类型的SelectNodes回报,无论是:

.SelectNodes("/p").SkipWhile(p => p.Class != "specific").Skip(1) 

.SelectNodes("/p").Cast<XX>().SkipWhile(p => p.Class != "specific").Skip(1) 

(或丑陋的版本)

.SelectNodes("/p").SkipWhile(p => ((XX)p).Class != "specific").Skip(1) 

(或在某些情况下 - 不,如果你的表情已经适当地过滤)

.SelectNodes("/p").OfType<XX>().SkipWhile(p => p.Class != "specific").Skip(1) 

编辑:我可能会创建一个扩展方法:

static class HapExtensions 
{ 
    public IEnumerable<T> SkipUntilAfter(this IEnumerable<T> sequence, Predicate<T> predicate) { 
     return sequence.SkipWhile(predicate).Skip(1); 
     } 
} 

人照顾搜索了这个现有技术?任何好的名字建议?

+0

SkipWhile很酷+1 – 2009-12-14 10:10:28

+0

这正是我所需要的。谢谢。 – morsanu 2009-12-14 10:35:39

+0

我很快就会使用它,所以谢谢你的询问! – 2009-12-14 11:49:06

2

使用。类在马克的例子试试这个

bool latterDayParagraphs = false; 
List<DocumentNode> nodes = new List<DocumentNode>(); 
foreach(var pElement in doc.DocumentNode.SelectNodes("/p")) 
{ 
    if(pElement.Class != "paragraph") 
    { 
     latterDayParagraphs = true; 
     continue; 
    } 
    if(latterDayParagraphs) 
    { 
     nodes.Add(pElement); 
    } 
} 
+0

我想你只是看了这个问题,并没有真正阅读它。 :)我使用HTML Agility Pack解析了C#中的HTML,并且我只需要选择带class =“paragraph”的p标签,后面跟class =“specific”的p标签。 – morsanu 2009-12-14 09:16:19

+0

对不起,希望这个答案更有用(你需要参考System.Linq)。 :) – 2009-12-14 09:31:51

+0

这将选择所有带有“段落”类的p标签。我只需要在class =“specific”的p标签之后的那些。 – morsanu 2009-12-14 09:37:13