iterparse variant that supports 'tag' parameter (like lxml),
    yields elements and clears nodes after parsing.
355062
def iterparse(source, tag, clear=False, events=None):
    
    for event, elem in ElementTree.iterparse(source, events=events):
        if elem.tag == tag:
            yield elem
        if clear:
            elem.clear()
1083131
def parse_Element(self, node):
        
        name = node.tagName
        ignores = self.ignores
        if name in ignores:
            return
        attr = "do_%s" % name
        if hasattr(self, attr):
            handlerMethod = getattr(self, attr)
            handlerMethod(node)
        else:
            self.generic_parse(node)
396374
def tags_with_text(xml, tags=None):
    """"""
    if tags is None:
        tags = []
    for element in xml:
        if element.text is not None:
            tags.append(element)
        elif len(element) > 0:  # pylint: disable=len-as-condition
            tags_with_text(element, tags)
        else:
            message = 'Unknown XML structure: {}'.format(element)
            raise ValueError(message)
    return tags
27054
function parse_loop(input, customTags) {
    add_tag("default");    
    i = 0;
    while(!input.eos()) {
      if (look(/@class\b/))
        at_class();
      else if (look(/@extends?\b/))
        at_extends()
      else if (look(/@inherits?\b/))
        at_inherits()
      else if (look(/@mixins?\b/))
        class_list_at_tag(/@mixins?/, "mixins");
      else if (look(/@alternateClassNames?\b/))
        class_list_at_tag(/@alternateClassNames?/, "alternateClassNames");
      else if (look(/@uses\b/))
        class_list_at_tag(/@uses/, "uses");
      else if (look(/@requires\b/))
        class_list_at_tag(/@requires/, "requires");
      else if (look(/@singleton\b/))
        boolean_at_tag(/@singleton/, "singleton");
      else if (look(/@event\b/))
        at_event();
      else if (look(/@method\b/))
        at_method();
      else if (look(/@constructor\b/))
        at_method(true);
      else if (look(/@attribute\b/))
        at_attribute();
      else if (look(/@binding\b/))
        at_binding();
      else if (look(/@param\b/))
        at_param();
      else if (look(/@returns?\b/))
        at_return();
      else if (look(/@cfg\b/))
        at_cfg();
      else if (look(/@property\b/))
        at_property();
      else if (look(/@type\s/))
        at_type();
      else if (look(/@xtype\b/))
        at_xtype(/@xtype/, "widget");
      else if (look(/@ftype\b/))
        at_xtype(/@ftype/, "feature");
      else if (look(/@ptype\b/))
        at_xtype(/@ptype/, "plugin");
      else if (look(/@member\b/))
        at_member();
      else if (look(/@inherit[dD]oc\b/))
        at_inheritdoc();
      else if (look(/@alias/))
        at_alias();
      else if (look(/@see/))
        at_see();
      else if (look(/@todo/))
        at_todo();
      else if (look(/@link/))
        at_link();
      else if (look(/@var\b/))
        at_var();
      else if (look(/@throws?\b/))
        at_throws();
      else if (look(/@enum\b/))
        at_enum();
      else if (look(/@override\b/))
        at_override();
      else if (look(/@cancelable\b/))
        at_cancelable();
      else if (look(/@author\b/))
        at_author();
      else if (look(/@version\b/))
        at_version();
      else if (look(/@since\b/))
        at_since();
      else if (look(/@deprecated\b/))
        at_deprecated();
      else if (look(/@related\b/))
        at_related();
      else if (look(/@private\b/))
        boolean_at_tag(/@private/, "private");
      else if (look(/@ignore\b/))
        boolean_at_tag(/@ignore/, "ignore");
      else if (look(/@experimental\b/))
        boolean_at_tag(/@experimental/, "experimental");
      else if (look(/@chainable\b/))
        boolean_at_tag(/@chainable/, "chainable");
      else if (look(/@inheritable\b/))
        boolean_at_tag(/@inheritable/, "inheritable");
      else if (look(/@accessor\b/))
        boolean_at_tag(/@accessor/, "accessor");
      else if (look(/@evented\b/))
        boolean_at_tag(/@evented/, "evented");
      else if (look(/@bubbles\b/))
        boolean_at_tag(/@bubbles/, "bubbles");
      else if (look(/@read\-?only\b/))
        boolean_at_tag(/@read\-?only/, "readonly");
      else if (look(/@default_private\b/))
        boolean_at_tag(/@default_private/, "default_private");
      else if (look(/@/)) {
        match(/@/);
        var tagName = look(/\w+/);

        var found = _.find(customTags, function(tag) {
          return RegExp(tag).test(tagName);
        });

        if (found) {
          match(found);
          add_tag(tagName);
          skip_horiz_white();

          if (look(/.*/).length > 0) 
            current_tag["doc"] = strip(match(/.*/)); // no text means it's a boolean
        }
        else {
          // basically, "@" has to be the first dang thing after the *
          // this resolves false positives, like [@read] 
          var currPos = input.pointer();
          input.setPointer(currPos - (tagName.length + 3));
         
          var startingLine = input.peek(tagName.length + 3);
         
          if (!/.@/.test(startingLine)) {
            console.warn("Warning".yellow + ": I found @" + tagName + ", but I'm not sure what it ought to do.");
          }

          input.setPointer(currPos);

          current_tag["doc"] += "@";
        }

      }
      else if (look(/[^@]/)) {
        current_tag["doc"] += match(/[^@]+/);
      }
    }
}
162215
def _parse_results(self, stream):
        """"""
        result = None
        values = None
        try:
            for event, elem in et.iterparse(stream, events=('start', 'end')):
                if elem.tag == 'results' and event == 'start':
                    # The wrapper element is a <results preview="0|1">. We
                    # don't care about it except to tell is whether these
                    # are preview results, or the final results from the
                    # search.
                    is_preview = elem.attrib['preview'] == '1'
                    self.is_preview = is_preview
                if elem.tag == 'result':
                    if event == 'start':
                        result = OrderedDict()
                    elif event == 'end':
                        yield result
                        result = None
                        elem.clear()

                elif elem.tag == 'field' and result is not None:
                    # We need the 'result is not None' check because
                    # 'field' is also the element name in the <meta>
                    # header that gives field order, which is not what we
                    # want at all.
                    if event == 'start':
                        values = []
                    elif event == 'end':
                        field_name = elem.attrib['k']
                        if len(values) == 1:
                            result[field_name] = values[0]
                        else:
                            result[field_name] = values
                        # Calling .clear() is necessary to let the
                        # element be garbage collected. Otherwise
                        # arbitrarily large results sets will use
                        # arbitrarily large memory intead of
                        # streaming.
                        elem.clear()

                elif elem.tag in ('text', 'v') and event == 'end':
                    try:
                        text = "".join(elem.itertext())
                    except AttributeError:
                        # Assume we're running in Python < 2.7, before itertext() was added
                        # So we'll define it here

                        def __itertext(self):
                          tag = self.tag
                          if not isinstance(tag, six.string_types) and tag is not None:
                              return
                          if self.text:
                              yield self.text
                          for e in self:
                              for s in __itertext(e):
                                  yield s
                              if e.tail:
                                  yield e.tail

                        text = "".join(__itertext(elem))
                    values.append(text)
                    elem.clear()

                elif elem.tag == 'msg':
                    if event == 'start':
                        msg_type = elem.attrib['type']
                    elif event == 'end':
                        text = elem.text if elem.text is not None else ""
                        yield Message(msg_type, text)
                        elem.clear()
        except SyntaxError as pe:
            # This is here to handle the same incorrect return from
            # splunk that is described in __init__.
            if 'no element found' in pe.msg:
                return
            else:
                raise
774069
def untlxml2py(untl_filename):
    
    # Create a stack to hold parents.
    parent_stack = []
    # Use iterparse to open the file and loop through elements.
    for event, element in iterparse(untl_filename, events=('start', 'end')):
        if NAMESPACE_REGEX.search(element.tag, 0):
            element_tag = NAMESPACE_REGEX.search(element.tag, 0).group(1)
        else:
            element_tag = element.tag
        # Process the element if it exists in UNTL.
        if element_tag in PYUNTL_DISPATCH:
            # If it is the element's opening tag,
            # add it to the parent stack.
            if event == 'start':
                parent_stack.append(PYUNTL_DISPATCH[element_tag]())
            # If it is the element's closing tag,
            # remove element from stack. Add qualifier and content.
            elif event == 'end':
                child = parent_stack.pop()
                if element.text is not None:
                    content = element.text.strip()
                    if content != '':
                        child.set_content(element.text)
                if element.get('qualifier', False):
                    child.set_qualifier(element.get('qualifier'))

                # Add the element to its parent.
                if len(parent_stack) > 0:
                    parent_stack[-1].add_child(child)
                # If it doesn't have a parent, it is the root element,
                # so return it.
                else:
                    return child
        else:
            raise PyuntlException(
                'Element "%s" not in UNTL dispatch.' % (element_tag)
            )
797014
def parse(source, remove_comments=True, **kw):
    """"""
    return ElementTree.parse(source, SourceLineParser(), **kw)
1289878
def parse_tag_collection(body)
        dom  = parse_and_validate_response(body, :root_name => 'tags')
        dom.root.elements.collect('tag') { |xml| Tag.from_rexml(xml) }
      end
124878
def generate_xmltags(fn, returntag, ignore_tags, ns=None):
    
    xmlns = create_namespace(ns)
    ns_ignore = ['{0}{1}'.format(xmlns, x) for x in ignore_tags]
    for ac, el in etree.iterparse(fn):
        if el.tag == '{0}{1}'.format(xmlns, returntag):
            yield el
        elif el.tag in ns_ignore:
            formatting.clear_el(el)
23465
function filterTags(tags, content) {
  if (!tags) {
    return content;
  }
  const $ = cheerio.load(content, { xmlMode: false });
  const tagOperations = tags.map(tag => ({
    // Trim leading + or -, replace * with .*, add ^ and $
    tagExp: `^${escapeRegExp(tag.replace(/^(\+|-)/g, '')).replace(/\\\*/, '.*')}$`,
    // Whether it is makes tags visible or hides them
    isHidden: tag.startsWith('-'),
  }));
  $('[tags]').each((i, element) => {
    $(element).attr('hidden', true);
    $(element).attr('tags').split(' ').forEach((tag) => {
      tagOperations.forEach((tagOperation) => {
        if (!tag.match(tagOperation.tagExp)) {
          return;
        }
        if (tagOperation.isHidden) {
          $(element).attr('hidden', true);
        } else {
          $(element).removeAttr('hidden');
        }
      });
    });
  });
  $('[hidden]').remove();
  return $.html();
}
1211876
private void processEndTag() throws XMLStreamException, TTException {
        mLevelInToShredder--;

        if (mInserted) {
            mInsertedEndTag = true;
        }

        if (mRemovedNode) {
            mRemovedNode = false;
        } else {

            // Move cursor to parent.
            if (mWtx.getNode().getDataKey() == mLastNodeKey) {
                /*
                 * An end tag must have been parsed immediately before and it
                 * must have been an empty element at the end of a subtree, thus
                 * move this time to parent node.
                 */
                assert mWtx.getNode().hasParent() && mWtx.getNode().getKind() == IConstants.ELEMENT;
                mWtx.moveTo(mWtx.getNode().getParentKey());
            } else {
                if (mWtx.getNode().getKind() == IConstants.ELEMENT) {
                    final ElementNode element = (ElementNode)mWtx.getNode();
                    if (element.hasFirstChild() && element.hasParent()) {
                        // It's not an empty element, thus move to parent.
                        mWtx.moveTo(mWtx.getNode().getParentKey());
                    }
                    // } else {
                    // checkIfLastNode(true);
                    // }
                } else if (((ITreeStructData)mWtx.getNode()).hasParent()) {
                    if (((ITreeStructData)mWtx.getNode()).hasRightSibling()) {
                        mWtx.moveTo(((ITreeStructData)mWtx.getNode()).getRightSiblingKey());
                        /*
                         * Means next event is an end tag in StAX reader, but
                         * something different where the Treetank transaction
                         * points to, which also means it has to be deleted.
                         */
                        mKeyMatches = -1;
                        mDelete = EDelete.ATBOTTOM;
                        deleteNode();
                    }
                    mWtx.moveTo(mWtx.getNode().getParentKey());
                }

            }

            mLastNodeKey = mWtx.getNode().getDataKey();

            // Move cursor to right sibling if it has one.
            if (((ITreeStructData)mWtx.getNode()).hasRightSibling()) {
                mWtx.moveTo(((ITreeStructData)mWtx.getNode()).getRightSiblingKey());
                mMovedToRightSibling = true;

                skipWhitespaces(mReader);
                if (mReader.peek().getEventType() == XMLStreamConstants.END_ELEMENT) {
                    /*
                     * Means next event is an end tag in StAX reader, but
                     * something different where the Treetank transaction points
                     * to, which also means it has to be deleted.
                     */
                    mKeyMatches = -1;
                    mDelete = EDelete.ATBOTTOM;
                    deleteNode();
                }
            } else {
                mMovedToRightSibling = false;
            }
        }
    }
220368
def strip_tags(cls, html):
        
        s = cls()
        s.feed(html)

        return s.get_data()
1287735
def iter_links_param_element(cls, element):
        ''''''
        valuetype = element.attrib.get('valuetype', '')

        if valuetype.lower() == 'ref' and 'value' in element.attrib:
            link_type = identify_link_type(element.attrib.get('value'))

            yield LinkInfo(
                element=element, tag=element.tag, attrib='value',
                link=element.attrib.get('value'),
                inline=True, linked=False,
                base_link=None,
                value_type='plain',
                link_type=link_type
            )
934524
private PatternElement parseNamedElement(Node el, Map<String, Scope> scopes) {
        PatternElement namedElement;
        if (
                nodeAttribute(el, TAG_VAR_ATTR_PARSE, DEFAULT_PARSE_VALUE)
                        && !nodeHasAttribute(el, TAG_VAR_ATTR_REGEX)
                        && !nodeHasAttribute(el, TAG_VAR_ATTR_ACTION)
                ) {
            namedElement = parseText(el, scopes);
        } else {
            namedElement = parseVariable(el);
        }
        return namedElement;
    }
1274584
def parse_nodes(nodes)
      output = ''

      # Short-circuit if it's empty
      return output if !nodes || nodes.empty?

      # Loop through nodes
      nodes.each do |node|
        case node.name
        when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
          level = node.name.match(/\Ah(\d)\Z/)[1].to_i
          if @options[:underline_headers] && level < 3
            content = parse_content(node)
            output << content + "\n"
            character = level == 1 ? '=' : '-'
            content.length.times { output << character}
          else
            hashes = ''
            level.times { hashes << '#' }
            output << "#{hashes} #{parse_content(node)}"
          end
        when 'blockquote'
          parse_content(node).split("\n").each do |line|
            output << "> #{line}\n"
          end
        when 'ul', 'ol'
          output << "\n\n" if @list.count > 0

          if unordered = node.name == 'ul'
            @list << :unordered
          else
            @list << :ordered
            @list_position << 0
          end

          output << parse_nodes(node.children)

          @list.pop
          @list_position.pop unless unordered
        when 'li'
          (@list.count - 1).times { output << '    ' }
          if @list.last == :unordered
            output << "* #{parse_content(node)}"
          else
            num = (@list_position[@list_position.count - 1] += 1)
            output << "#{num}. #{parse_content(node)}"
          end
        when 'pre'
          content = parse_content(node)

          if @options[:fenced_code_blocks]
            output << "```\n#{content}\n```"
          else
            content.split("\n").each do |line|
              output << "    #{line}\n"
            end
          end
        when 'hr'
          output << "---\n\n"
        when 'a'
          output << "[#{parse_content(node)}](#{node['href']}#{build_title(node)})"
        when 'i', 'em'
          output << "*#{parse_content(node)}*"
        when 'b', 'strong'
          output << "**#{parse_content(node)}**"
        when 'u'
          output << "_#{parse_content(node)}_"
        when 'mark'
          output << "==#{parse_content(node)}=="
        when 'code'
          output << "`#{parse_content(node)}`"
        when 'img'
          output << "![#{node['alt']}](#{node['src']}#{build_title(node)})"
        when 'text'
          content = parse_content(node)

          # Optionally look for links
          content.gsub!(AUTOLINK_URL_REGEX, '<\1>') if @options[:autolink]
          content.gsub!(AUTOLINK_EMAIL_REGEX, '<\1>') if @options[:autolink]

          output << content
        when 'script'
          next unless @options[:allow_scripts]
          output << node.to_html
        else
          # If it's an supported node or a node that just contains text, just get
          # its content
          output << parse_content(node)
        end

        output << "\n\n" if BLOCK_ELEMENT_NAMES.include?(node.name)
      end

      output
    end
1070434
def clear_element(parent_to_parse, element_path=None):
    

    element = get_element(parent_to_parse, element_path)

    if element is None:
        return parent_to_parse
    else:
        element.clear()

    return element
585370
function(markup, targetdoc) {
		return this.parseToNodes(markup, targetdoc).filter(function(node) {
			return node.nodeType === Node.ELEMENT_NODE;
		});
	}