Perform an XPath on an element and indicate if we need to loop over it to find something

    :param parent: XML Node on which to perform XPath
    :param xpath: XPath to run
    :return: (Result, Need to loop Indicator)
553144
def performXpath(parent, xpath):
    
    loop = False
    if xpath.startswith(".//"):
        result = parent.xpath(
            xpath.replace(".//", "./", 1),
            namespaces=XPATH_NAMESPACES
        )
        if len(result) == 0:
            result = parent.xpath(
                "*[{}]".format(xpath),
                namespaces=XPATH_NAMESPACES
            )
            loop = True
    else:
        result = parent.xpath(
            xpath,
            namespaces=XPATH_NAMESPACES
        )
    return result[0], loop
1190329
def child_xpath(ns, element_name, attributes=nil)
      ns_uri = ns.is_a?(Namespace) ? ns.uri : ns
      unless !attributes.nil? && attributes.is_a?(Hash)
        "child::*[local-name()='#{element_name}' and namespace-uri()='#{ns_uri}']"
      else
        attr_str = attributes.collect{|key, val| "@#{key.to_s}='#{val}'"}.join(' and ')
        "child::*[local-name()='#{element_name}' and namespace-uri()='#{ns_uri}' and #{attr_str}]"
      end
    end
669181
def check_content(content, **kwargs):
    ''''''
    # valid html root tag
    try:
        # render elements tree from content
        tree = fragment_fromstring(content)
        # flag for prevent content rerendering, when no "active" urls found
        processed = False
        # django > 1.5 template boolean\None variables feature
        if isinstance(kwargs['parent_tag'], bool):
            if not kwargs['parent_tag']:
                kwargs['parent_tag'] = 'self'
            else:
                raise ImproperlyConfigured('''
                    parent_tag=True is not allowed
                ''')
        elif kwargs['parent_tag'] is None:
            kwargs['parent_tag'] = 'self'
        # if parent_tag is False\None\''\a\self
        # "active" status will be applied directly to "<a>"
        if kwargs['parent_tag'].lower() in ('a', 'self', ''):
            # xpath query to get all "<a>"
            urls = tree.xpath('.//a')
            # check "active" status for all urls
            for url in urls:
                if check_active(url, url, **kwargs):
                    # mark flag for rerendering content
                    processed = True
        # otherwise css_class must be applied to parent_tag
        else:
            # xpath query to get all parent tags
            elements = tree.xpath('.//{parent_tag}'.format(
                parent_tag=kwargs['parent_tag'],
            ))
            # check all elements for "active" "<a>"
            for element in elements:
                # xpath query to get all "<a>"
                urls = element.xpath('.//a')
                # check "active" status for all urls
                for url in urls:
                    if check_active(url, element, **kwargs):
                        # flag for rerendering content tree
                        processed = True
                        # stop checking other "<a>"
                        break
        # do not rerender content if no "active" urls found
        if processed:
            # render content from tree
            return tostring(tree, encoding='unicode')
    # not valid html root tag
    except ParserError:
        # raise an exception with configuration example
        raise ImproperlyConfigured('''
            content of {% activeurl %} must have valid html root tag
            for example
                {% activeurl %}
                    <ul>
                        <li>
                            <a href="/page/">page</a>
                        </li>
                        <li>
                            <a href="/other_page/">other_page</a>
                        </li>
                    </ul>
                {% endactiveurl %}
            in this case <ul> is valid content root tag
        ''')
    return content
839477
def parse(node)
      node.xpath('*').each do |node_child|
        case node_child.name
        when 'p'
          @elements << DocxParagraph.new(parent: self).parse(node_child)
        when 'r'
          @elements << ParagraphRun.new(parent: self).parse(node_child)
        when 'tbl'
          @elements << Table.new(parent: self).parse(node_child)
        end
      end
      self
    end
923111
def get_elements(parent_to_parse, element_path):
    

    element = get_element(parent_to_parse)

    if element is None or not element_path:
        return []

    return element.findall(element_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]
932663
def get_xpath_root(xpath):
    

    if xpath:
        if xpath.startswith('@'):
            xpath = ''
        else:
            index = xpath.find('/@' if '@' in xpath else '/{')
            xpath = xpath[:index] if index >= 0 else xpath

    return xpath
500607
def search_current_el xpath
      # try to find the rule in the current verb
      desired_el = @current_el.at_xpath xpath
      return desired_el unless desired_el.nil?
      
      # check all the verb's parents, walking up the hierarchy
      @current_el_parents.each do |parent|
        desired_el = parent.at_xpath xpath
        return desired_el unless desired_el.nil?
      end
      
      nil
    end
393167
function searchParent(el, parentClass) {
    var found = false;
    var parentElement = el.parentNode;
    while (parentElement && found === false) {
      if (hasClass(parentElement, parentClass) === true) {
        found = true;
      } else {
        parentElement = parentElement.parentNode;
      }
    }
    if (found === true) {
      return parentElement.getAttribute('id');
    } else {
      return '';
    }
  }
13813
@Override
    Object parent() {
        if (length() == 0) return Undefined.instance;

        XML candidateParent = null;

        for (int i = 0; i < length(); i++) {
            Object currParent = getXmlFromAnnotation(i).parent();
            if (!(currParent instanceof XML)) return Undefined.instance;
            XML xml = (XML)currParent;
            if (i == 0) {
                // Set the first for the rest to compare to.
                candidateParent = xml;
            } else {
                if (candidateParent.is(xml)) {
                    //    keep looking
                } else {
                    return Undefined.instance;
                }
            }
        }
        return candidateParent;
    }
282266
def _child(element, child_tagname):
    
    xpath = './%s' % child_tagname
    matching_children = element.xpath(xpath, namespaces=nsmap)
    return matching_children[0] if len(matching_children) else None
346743
def xsl_text(self, text, parent):
        
        res = ET.SubElement(parent, "text")
        res.text = text
        return res
1171526
def _load_xml(self):
        
        if self._xml is not None:
            return
        matcher = "\[(?:Normal|Conditional) Substitution\(index=(\d+), type=\d+\)\]"
        self._xml = re.sub(matcher, "{\\1:}",
                           self._template_node.template_format().replace("{", "{{").replace("}", "}}"))
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
        )
1362663
def get_xpath_branch(xroot, xpath):
    

    if xroot and xpath and xpath.startswith(xroot):
        xpath = xpath[len(xroot):]
        xpath = xpath.lstrip(XPATH_DELIM)

    return xpath
551429
def parent
      assert_exists

      e = @element.parent

      if e.kind_of?(Nokogiri::XML::Element)
        WatirNokogiri.element_class_for(e.node_name.downcase).new(@parent, :element => e)
      end
    end
1025839
function(doc, nodes, selector, after) {
        var parent = module.exports.resolveParent(doc, selector);
        if (!parent) {
            //Try to create the parent recursively if necessary
            try {
                var parentToCreate = et.XML('<' + path.basename(selector) + '>'),
                    parentSelector = path.dirname(selector);

                this.graftXML(doc, [parentToCreate], parentSelector);
            } catch (e) {
                return false;
            }
            parent = module.exports.resolveParent(doc, selector);
            if (!parent) return false;
        }

        nodes.forEach(function (node) {
            // check if child is unique first
            if (uniqueChild(node, parent)) {
                var children = parent.getchildren();
                var insertIdx = after ? findInsertIdx(children, after) : children.length;

                //TODO: replace with parent.insert after the bug in ElementTree is fixed
                parent.getchildren().splice(insertIdx, 0, node);
            }
        });

        return true;
    }