Suppose the input XML is
<root>
<entry>
<title>Test</title>
<author>Me</author>
</entry>
</root>
I would like to find the lowest common ancestor of title
and author
.
I tried the following code in BaseX:
let $p := doc('t.xq')//title,
$q := doc('t.xq')//author,
$cla := ($p/ancestor-or-self::node() intersect $q/ancestor-or-self::node())
return
$cla
But it returns nothing (blank output).
Your code works totally fine for me, apart from returning all common ancestors.
The Last Common Ancestor
Since they're returned in document order and the last common ancestor must also be the last node, simply extend with a
[last()]
predicate.Files and Databases
If the query you posted does not return anything, you might be working on a file
t.xq
.intersect
requires all nodes to be compared in the same database, each invocation ofdoc(...)
on a file creates a new in-memory database. Either create a database in BaseX with the contents, or do something likeand replace subsequent
doc(...)
calls by$doc
(which now references a single in-memory database created for the file).