Skip to content

Instantly share code, notes, and snippets.

@CanOfBees
Last active October 17, 2020 01:28
Show Gist options
  • Save CanOfBees/8cfb435ac06986c9b0b0c215a786f4d7 to your computer and use it in GitHub Desktop.
Save CanOfBees/8cfb435ac06986c9b0b0c215a786f4d7 to your computer and use it in GitHub Desktop.
BaseX - return distinct XPaths as strings
xquery version "3.1";
declare variable $input :=
<test>
<aaa>
<bbb type="foo">bbb content</bbb>
</aaa>
<aaa>
<bbb type="foo" enc="bar">bbb content</bbb>
</aaa>
<aaa>
<bbb type="bzz" enc="bar">bbb content</bbb>
<bbb type="qux" enc="bar" key="yes" point="start">bbb content</bbb>
<bbb type="qux" enc="bar" key="yes" point="end">bbb content</bbb>
</aaa>
</test>;
declare function local:e2(
$nodes as node()*
) as xs:string* {
for $node in $nodes
let $self := name($node)
return(
string-join(
if ($node/@*)
then (string-join($self || string-join(for $att in $node/@* return local:atty($att))), local:e2($node/child::*))
else (string-join($self, "/"), local:e2($node/child::*)), "/"),
out:nl()
)
};
declare function local:atty(
$att as attribute()
) as xs:string* {
"[@" || name($att) || "='" || data($att) || "']"
};
local:e2($input)
(:
this currently returns
test/aaa/bbb[@type='foo']/
/
/aaa/bbb[@type='foo'][@enc='bar']/
/
/aaa/bbb[@type='bzz'][@enc='bar']/
/bbb[@type='qux'][@enc='bar'][@key='yes'][@point='start']/
/bbb[@type='qux'][@enc='bar'][@key='yes'][@point='end']/
/
:)
xquery version "3.1";
(: and Andy Bunce with the expert guidance, getting me on track with HOF(FTW!)! :)
declare variable $input :=
<test>
<aaa>
<bbb type="foo">bbb content</bbb>
</aaa>
<aaa>
<bbb type="foo" enc="bar">bbb content</bbb>
</aaa>
<aaa>
<bbb type="bzz" enc="bar">bbb content</bbb>
<bbb type="qux" enc="bar" key="yes" point="start">bbb content</bbb>
<bbb type="qux" enc="bar" key="yes" point="end">bbb content</bbb>
</aaa>
</test>;
declare function local:pb(
$result as xs:string,
$node as node()
) {
concat(
$result, "/"[$result], name($node),
$node/@* ! local:atty(.) => string-join("")
)
};
declare function local:atty(
$att as attribute()
) as xs:string* {
"[@" || name($att) || "='" || data($att) || "']"
};
distinct-values(
$input//* ! fold-left(ancestor-or-self::*, '', local:pb(?, ?))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment