An XPath-like interface to `query`.
762348
def querypath(self, block, path):
        """"""
        class BadPath(Exception):
            """Bad path exception thrown when path cannot be found."""
            pass
        results = self.query(block)
        ROOT, SEP, WORD, FINAL = six.moves.range(4)               # pylint: disable=C0103
        state = ROOT
        lexer = RegexLexer(
            ("dotdot", r"\.\."),
            ("dot", r"\."),
            ("slashslash", r"//"),
            ("slash", r"/"),
            ("atword", r"@\w+"),
            ("word", r"\w+"),
            ("err", r"."),
        )
        for tokname, toktext in lexer.lex(path):
            if state == FINAL:
                # Shouldn't be any tokens after a last token.
                raise BadPath()
            if tokname == "dotdot":
                # .. (parent)
                if state == WORD:
                    raise BadPath()
                results = results.parent()
                state = WORD
            elif tokname == "dot":
                # . (current node)
                if state == WORD:
                    raise BadPath()
                state = WORD
            elif tokname == "slashslash":
                # // (descendants)
                if state == SEP:
                    raise BadPath()
                if state == ROOT:
                    raise NotImplementedError()
                results = results.descendants()
                state = SEP
            elif tokname == "slash":
                # / (here)
                if state == SEP:
                    raise BadPath()
                if state == ROOT:
                    raise NotImplementedError()
                state = SEP
            elif tokname == "atword":
                # @xxx (attribute access)
                if state != SEP:
                    raise BadPath()
                results = results.attr(toktext[1:])
                state = FINAL
            elif tokname == "word":
                # xxx (tag selection)
                if state != SEP:
                    raise BadPath()
                results = results.children().tagged(toktext)
                state = WORD
            else:
                raise BadPath("Invalid thing: %r" % toktext)
        return results
565191
def selector_to_xpath(cls, selector, xmlns=None):
        
        selector = selector.replace(' .', ' *.')
        if selector[0] == '.':
            selector = '*' + selector
            log.debug(selector)
        
        if '#' in selector:
            selector = selector.replace('#', '*#')
            log.debug(selector)

        if xmlns is not None:
            prefix = list(xmlns.keys())[0]
            href = xmlns[prefix]
            selector = ' '.join([
                (n.strip() != '>' and prefix + '|' + n.strip() or n.strip())
                for n in selector.split(' ')
                ])
            log.debug(selector)
        
        path = cssselect.GenericTranslator().css_to_xpath(selector)
        path = path.replace("descendant-or-self::", "")
        path = path.replace("/descendant::", "//")
        path = path.replace('/*/', '//')
        
        log.debug(' ==> %s' % path)
        
        return path
110465
def xpath(self, xpath):
    
    return [self.get_node_factory().create(node_id)
            for node_id in self._get_xpath_ids(xpath).split(",")
            if node_id]
1123134
def find_xml_all(cls, url, markup, tag, pattern):
        
        body = cls.find_xml(url, markup)
        return body.find_all(tag, href=re.compile(pattern))
567198
def build_query_fragment(query):
    
    root = etree.Element('query', nsmap={None: 'http://basex.org/rest'})
    text = etree.SubElement(root, 'text')
    text.text = etree.CDATA(query.strip())
    return root
1309420
def select(*queries, **kwargs):
    
    def make_query(*args):
        def simple_query(nodes):
            if len(args) == 0:
                return nodes
            pred = args[0]
            results = []
            if isinstance(pred, list):
                funcs = [make_query(q) for q in pred]
                return __or(funcs, nodes)
            elif isinstance(pred, tuple):
                name, attrs = pred[0], pred[1:]
                name_pred = __make_name_pred(name)
                attrs_pred = __make_attrs_pred(attrs)
                for n in nodes:
                    if name_pred(n.name) and attrs_pred(n.attrs):
                        results.append(n)
            else:
                name_pred = __make_name_pred(pred)
                for n in nodes:
                    if name_pred(n.name):
                        results.append(n)
            return results
        if len(args) > 1:
            return __compose(make_query(*args[1:]), simple_query)
        return simple_query

    def deep_query(query, nodes):
        """ Slide the query down the branches. """
        def inner(children):
            results = []
            for c in children:
                if query([c]):
                    results.append(c)
                results.extend(inner(c.children))
            return results
        return inner(nodes)

    def unique(roots):
        seen = set()
        results = []
        for r in roots:
            if r not in seen:
                seen.add(r)
                results.append(r)
        return results

    def compiled_query(nodes):
        """
        This is the compiled query that can be run against a configuration.
        """
        query = make_query(*queries)

        roots = kwargs.get("roots", True)
        if kwargs.get("deep", False):
            results = deep_query(query, nodes)
            if roots:
                results = unique([r.root for r in results])
        elif roots:
            results = unique([n.root for n in query(nodes)])
        else:
            results = query(nodes)

        one = kwargs.get("one")
        if one is None:
            return SearchResult(children=results)
        return results[one] if results else None
    return compiled_query
765311
def _query(options, collection_name, num_to_skip,
           num_to_return, query, field_selector, opts, check_keys):
    """"""
    encoded = _dict_to_bson(query, check_keys, opts)
    if field_selector:
        efs = _dict_to_bson(field_selector, False, opts)
    else:
        efs = b""
    max_bson_size = max(len(encoded), len(efs))
    return b"".join([
        _pack_int(options),
        _make_c_string(collection_name),
        _pack_int(num_to_skip),
        _pack_int(num_to_return),
        encoded,
        efs]), max_bson_size
1318709
def get_match(self, elem):
        """"""
        for m in self.matches:
            if (m.expression is not None and eval(m.expression)==True) \
            or (m.xpath is not None and len(elem.xpath(m.xpath, namespaces=m.namespaces)) > 0):
                LOG.debug("=> match: %r" % m.expression)
                return m
1267319
def _fetch_xml(self, url):
        """"""
        with contextlib.closing(urlopen(url)) as f:
            return xml.etree.ElementTree.parse(f).getroot()
672360
def xpath(request):
    """"""
    ident_hash = request.params.get('id')
    xpath_string = request.params.get('q')

    if not ident_hash or not xpath_string:
        exc = httpexceptions.HTTPBadRequest
        exc.explanation = 'You must supply both a UUID and an xpath'
        raise exc

    try:
        uuid, version = split_ident_hash(ident_hash)
    except IdentHashShortId as e:
        uuid = get_uuid(e.id)
        version = e.version
    except IdentHashMissingVersion as e:
        uuid = e.id
        version = get_latest_version(e.id)
    except IdentHashSyntaxError:
        raise httpexceptions.HTTPBadRequest

    settings = get_current_registry().settings
    with db_connect() as db_connection:
        with db_connection.cursor() as cursor:
            result = get_content_metadata(uuid, version, cursor)

    resp = request.response

    if result['mediaType'] == COLLECTION_MIMETYPE:
        matched_route = request.matched_route.name
        results = xpath_book(request, uuid, version,
                             return_json=matched_route.endswith('json'))
        if matched_route.endswith('json'):
            results = {'results': list(results)}
            resp.body = json.dumps(results)
            resp.content_type = 'application/json'
        else:
            resp.body = results
            resp.content_type = 'application/xhtml+xml'
    else:
        results = {'results': list(xpath_page(request, uuid, version))}
        resp.body = json.dumps(results)
        resp.content_type = 'application/json'

    resp.status = "200 OK"
    return resp
122682
function query(element, elementQuery) {
  if (!element.content) {
    return [];
  }

  if (!lodash.isArray(element.content)) {
    return [];
  }

  const results = lodash.where(element.content, elementQuery);

  return lodash
    .chain(element.content)
    .map((nestedElement) => {
      return query(nestedElement, elementQuery);
    })
    .flatten()
    .concat(results)
    .value();
}
292420
def xpath_evaluator(self, namespaces=None, regexp=False, smart_strings=True):
        
        """
        return etree.XPathEvaluator(
            self._xml,
            namespaces=namespaces,
            regexp=regexp,
            smart_strings=smart_strings
        )
1101117
function DOMQuery(elements, context) {
  this.length = elements.length
  this.context = context
  var self = this
  each(elements, function(i) { self[i] = this })
}
1039157
function( query, elements ){
        if( query != null ){
          var matches = false;
          elements = elements(); // make elements functional so we save cycles if query == null

          // query must match for at least one element (may be recursive)
          for(var i = 0; i < elements.size(); i++){
            if( queryMatches( query, elements.eq(i) ) ){
              matches = true;
              break;
            }
          }

          return matches;
        } else {
          return true;
        }
      }
651236
def find_elements_by_xpath(self, xpath):
        
        from sdklib.html.elem import ElemLxml

        elements = self.html_obj.xpath(xpath)
        return [ElemLxml(e) for e in elements]
681006
def queryHTML(self, path):
        """"""
        if etree is None:
            raise Exception("lxml not available")
        document = etree.HTML(self.contents)
        for node in document.xpath(path):
            if isinstance(node, basestring):
                print node
            else:
                print etree.tostring(node, pretty_print=True).strip()
422497
public void doXml(StaplerRequest req, StaplerResponse rsp,
                      @QueryParameter String xpath,
                      @QueryParameter String wrapper,
                      @QueryParameter String tree,
                      @QueryParameter int depth) throws IOException, ServletException {
        setHeaders(rsp);

        String[] excludes = req.getParameterValues("exclude");

        if(xpath==null && excludes==null) {
            // serve the whole thing
            rsp.serveExposedBean(req,bean,Flavor.XML);
            return;
        }

        StringWriter sw = new StringWriter();

        // first write to String
        Model p = MODEL_BUILDER.get(bean.getClass());
        TreePruner pruner = (tree!=null) ? new NamedPathPruner(tree) : new ByDepth(1 - depth);
        p.writeTo(bean,pruner,Flavor.XML.createDataWriter(bean,sw));

        // apply XPath
        FilteredFunctionContext functionContext = new FilteredFunctionContext();
        Object result;
        try {
            Document dom = new SAXReader().read(new StringReader(sw.toString()));
            // apply exclusions
            if (excludes!=null) {
                for (String exclude : excludes) {
                    XPath xExclude = dom.createXPath(exclude);
                    xExclude.setFunctionContext(functionContext);
                    List<org.dom4j.Node> list = (List<org.dom4j.Node>)xExclude.selectNodes(dom);
                    for (org.dom4j.Node n : list) {
                        Element parent = n.getParent();
                        if(parent!=null)
                            parent.remove(n);
                    }
                }
            }
            
            if(xpath==null) {
            	result = dom;
            } else {
                XPath comp = dom.createXPath(xpath);
                comp.setFunctionContext(functionContext);
                List list = comp.selectNodes(dom);

                if (wrapper!=null) {
                    // check if the wrapper is a valid entity name
                    // First position:  letter or underscore
                    // Other positions: \w (letter, number, underscore), dash or dot
                    String validNameRE = "^[a-zA-Z_][\\w-\\.]*$";

                    if(!wrapper.matches(validNameRE)) {
                        rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                        rsp.getWriter().print(Messages.Api_WrapperParamInvalid());
                        return;
                    }

                    Element root = DocumentFactory.getInstance().createElement(wrapper);
                    for (Object o : list) {
                        if (o instanceof String) {
                            root.addText(o.toString());
                        } else {
                            root.add(((org.dom4j.Node)o).detach());
                        }
                    }
                    result = root;
                } else if (list.isEmpty()) {
                    rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    rsp.getWriter().print(Messages.Api_NoXPathMatch(xpath));
                    return;
                } else if (list.size() > 1) {
                    rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    rsp.getWriter().print(Messages.Api_MultipleMatch(xpath,list.size()));
                    return;
                } else {
                    result = list.get(0);
                }
            }

        } catch (DocumentException e) {
            LOGGER.log(Level.FINER, "Failed to do XPath/wrapper handling. XML is as follows:"+sw, e);
            throw new IOException("Failed to do XPath/wrapper handling. Turn on FINER logging to view XML.",e);
        }


        if (isSimpleOutput(result) && !permit(req)) {
            // simple output prohibited
            rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "primitive XPath result sets forbidden; implement jenkins.security.SecureRequester");
            return;
        }

        // switch to gzipped output
        try (OutputStream o = rsp.getCompressedOutputStream(req)) {
            if (isSimpleOutput(result)) {
                // simple output allowed
                rsp.setContentType("text/plain;charset=UTF-8");
                String text = result instanceof CharacterData ? ((CharacterData) result).getText() : result.toString();
                o.write(text.getBytes(StandardCharsets.UTF_8));
                return;
            }

            // otherwise XML
            rsp.setContentType("application/xml;charset=UTF-8");
            new XMLWriter(o).write(result);
        }
    }