def find_xpath(xpath, tree, namespaces={}, **kwargs):
    """
    Find elements within an XML tree whose attributes match certain
    values.

    :param xpath: an xpath query string.
    :param tree: `xml.etree.ElementTree` object.
    :param namespaces: a dictionary of namespace prefixes.
    :param kwargs: specifies attribute values to filter by.

    :return: An iterator over valid elements.
    """
    elements = tree.iterfind(xpath, namespaces=namespaces)
    if not kwargs:
        return elements
    else:
        query = set(kwargs.items())
        return (i for i in elements if query.issubset(set(i.attrib.items())))