Search code examples
xpathxquery

XPath to match all elements in an array


I am trying to write a condition that applies if an element contains all the attributes in a predefined list but I can not seem to get the XPath correct.

Example data:

let $element := <country type="" class="" ref="" ana=""/>
return 
    if($element/@*[local-name() = ('type', 'class', 'ref', 'ana')]) then 
        'All attributes are present'
    else 'You can add attributes'

The first condition returns true if any of the attributes are present, I'm not sure what the correct XPath is to make sure they are all present.

Thanks, Winona


Solution

  • If it's a literal list I would just use and:

    if ($element[@type and @class and @ref and @ana]) ...
    

    If the list is not known statically, you can use every

    if (every $name in $list satisfies exists($element/@*[local-name()=$name])) ...
    

    or more concisely (but less readably)

    if ($list[not(. = $element/@*/local-name())]) ...
    

    Another option is:

    if (count($element/@*[local-name()=$list]) = count($list)) ...