How to join two HtmlNodeCollections

c# html-agility-pack xpath

Question

I'm usign HTML Agility Pack in C# and I have two HtmlNodeCollection. Can I join both or is there other ways to get both in one HtmlNodeCollection?

One:

HtmlNodeCollection butiks = doc.DocumentNode.SelectNodes("//div[contains(@class,'butik-large-image')]");

Two:

HtmlNodeCollection butiks = doc.DocumentNode.SelectNodes("//div[contains(@class,'butik small left')]");

Accepted Answer

HtmlNodeCollection inherits IList<HtmlNode> which inherits IEnumerable<HtmlNode> on which you can call the Enumerable.Concat() extension method to create a new enumerable containing both sources. See How to concatenate two IEnumerable<T> into a new IEnumerable<T>?.

You can also just select both sets of nodes by using an "or" in your Xpath expression:

//div[contains(@class,'butik-large-image') or contains(@class,'butik small left')]

Please note this contains() expects given classes in the given order. If you don't want that, use parentheses and and:

//div[contains(@class,'butik-large-image') 
or 
( 
    contains(@class,'left') and
    contains(@class,'small') and
    contains(@class,'butik')
)]

See How can I select an element with multiple classes with Xpath? for a proper implementation of that and, as above code will match false positives because it doesn't check for the classes as separate words.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why