No1Lives4Ever
No1Lives4Ever

Reputation: 6883

XPath : All divs which not have a specific child

I'm have HTML file and I'm parsing it with XPath. I'm want to select all [div] nodes which not have [p] tag(s) in it.

For example, input:

<div>
    <p>no1</p>
</div>
<div>
    <div>
        <p>no2</p>
    </div>
</div>
<div>
    yes!!!
</div>

Expected output:

yes!!!

I'm tried this XPath query, which not working for me:

//div[not (p)]

Upvotes: 1

Views: 1939

Answers (2)

William Walseth
William Walseth

Reputation: 2923

Use //div[not(descendant::p)]

Here's a quick XSL sample

<xsl:template match='/'>
<div>
<xsl:for-each select='//div[not(descendant::p)]'>
    <xsl:value-of select='.'/>
</xsl:for-each>
</div>
</xsl:template>

Upvotes: 4

StuartLC
StuartLC

Reputation: 107237

The xpath:

//div[not (p)]

returns 2 div Nodes in your sample xml:

<div>  <-- This one
    <div>

and your expected one:

<div>
    yes!!!
</div>

You are possibly referencing the xpath in a query where you are expecting just a single node (e.g. SelectSingleNode) and therefore just the first node is returned.

Upvotes: 0

Related Questions