Home > Software engineering >  Exclude elements from Xpath groups
Exclude elements from Xpath groups

Time:12-08

I have a very complex HTML of a website. I want to select multiple groups of elements by relative Xpath. For example:

//div[@otherthing"]

Once I have all elements selected I want to exclude some specific elements within the same xpath.

Let's say the xpath above returned 150 elements as a result. I want to exclude the following 3 xpaths which all point to 1 element each. So the end result should be 147 elements found:

//div[@id="menu"]

//div/span/div[@]

//body/span/div/span/div[1]

How can I do this within 1 xpath with Xpath 1?

I have tried the solution here, however this only works while you are selecting one group you would like to exclude from: https://stackoverflow.com/a/74615054/12366148

I have also tried multiple ways to combine the 'not' and 'self' commands, however nothing seems to work. I can't use the except operator unfortunately as that only works in Xpath 2.0.

CodePudding user response:

Given <xsl:variable name="ns1" select='//div[@otherthing"]'/> and <xsl:variable name="ns2" select='//div[@id="menu"] | //div/span/div[@] | //body/span/div/span/div[1]'/>, you can use e.g.

<xsl:variable name="ns1-except-ns2" select="$ns1[count(. | $ns2) != count($ns2)]"/>

if my XPath 1 recollection still works.

You haven't used an XSLT tag so I guess you want

(//div[@otherthing"])[count(. | //div[@id="menu"] | //div/span/div[@] | //body/span/div/span/div[1]) != count(//div[@id="menu"] | //div/span/div[@] | //body/span/div/span/div[1])]
  • Related