Solved

# What's the XPath for this example?

Posted on 2013-06-06
258 Views
What's the XPath for grabbing a "<DIV id="myid">...</div>" piece of an html page and only if there are 2 to 5 nested DIVs?
0
Question by:lucavilla
• 3
• 2

LVL 60

Accepted Solution

Geert Bormans earned 500 total points
//DIV[@id = 'myid'][count(ancestor::DIV) >= 2 and count(ancestor::DIV) <= 5 ]
if you mean nested inside 2 to 5 div

//DIV[@id = 'myid'][count(descendant::DIV) >= 2 and count(descendant::DIV) <= 5 ]
if you mean to have nested inside 2 to 5 div

//DIV[@id = 'myid'][(count(ancestor::DIV) + count(descendant::DIV)) >= 2 and ][(count(ancestor::DIV) + count(descendant::DIV))  <= 5 ]
if you need it to be inside a sequence of 2 to five div
0

Author Comment

Great Gertone!

Only a problem because I was not clear in my question.  How can I adapt your second solution to count only the *levels* of sub-DIVs?

Example:
<div>abc
<div>def
</div>ghi
<div>lmn
</div>opq
</div>

Your solution counts 2 descendant DIVs.
How can I tell you count only the sub-levels of DIVs, i.e. 1?
0

LVL 60

Expert Comment

mmh, then it gets tricky

you could test for
//DIV[@id = 'myid'][DIV/DIV| DIV/DIV/DIV| DIV/DIV/DIV/DIV| DIV/DIV/DIV/DIV/DIV ]
bit clumsy, I know, I hope you don't have to do this for 2 to 40 :-)

the other way is to go as deep as possible and look up (that is the only ay to cound a single path), but that only works as a replaement for the third situation
0

Author Comment

Wow thanks it works, you're a genius!  and thanks to you I'm starting to love this (still unknown to me) XPATH, I start to read a tutorial to learn it!
0

LVL 60

Expert Comment

welcome
0

## Featured Post

### Suggested Solutions

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Browsing the questions asked to the Experts of this forum, you will be amazed to see how many times people are headaching about monster regular expressions (regex) to select that specific part of some HTML or XML file they want to extract. The examp…
In this tutorial viewers will learn how to position overlapping items using z-index in CSS. They will also learn the restrictions on the z-index property.  Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Red.…
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …