query the depth of the lowest node?

P

Phlip

xmlists:

Here's a chestnut from graph theory:

What's the minimum XPath(s) - hence the most efficient way - to query the depth
of the lowest node?

All I can think of is calling count(ancestor::*) on every node...
 
M

Martin Honnen

Phlip said:
What's the minimum XPath(s) - hence the most efficient way - to query
the depth of the lowest node?

All I can think of is calling count(ancestor::*) on every node...

With XQuery 1.0 or XPath 2.0 you can do
max(for $el in descendant::* return count($el/ancestor-or-self::*))
That assumes you are interested in element nodes but could obviously be
changed to select other node types.
 
M

Martin Honnen

Martin said:
With XQuery 1.0 or XPath 2.0 you can do
max(for $el in descendant::* return count($el/ancestor-or-self::*))

max(for $el in descendant::*[not(*)] return count($el/ancestor-or-self::*))

should be slightly more efficient.
 
P

Phlip

max(for $el in descendant::*[not(*)] return count($el/ancestor-or-self::*))

While I go smack around the author of Nokogiri to let me return a count instead
of a nodeset...

Does the extant libxml2 do XPath 2.0? And can anyone think of a version that
returns a nodeset?

Until then, I will just use 'descendant::*[not(*)]' to get a nodeset with each
leaf node, then use 'count(ancestor-or-self::*)'. That's better than ON time,
because it's just On where n is the number of leaves...
 
P

Phlip

Until then, I will just use 'descendant::*[not(*)]' to get a nodeset
with each leaf node, then use 'count(ancestor-or-self::*)'. That's
better than ON time, because it's just On where n is the number of
leaves...

def maximum_depth
@builder.doc.xpath('descendant::*[not(*)]').
map{|e| e.xpath('ancestor-or-self::*').length }.
sort.last
end

Yup worked like a charm the first time. Thanks, guys!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top