XPath : All divs which not have a specific child

1.9k views Asked by At

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)]
2

There are 2 answers

0
StuartLC On

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.

1
William Walseth On

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>