translate the xml rules in to specific predicates to return RuleExceHandler
428268
public CompositeExceptionHandler buildHandlersFor(XmlRules rules) {
    ImmutableList.Builder<RuleExceptionHandler> builder = ImmutableList.builder();
    for (XmlRules.ExceptionRule rule : rules.getExceptionRules()) {
      builder.add(buildHandlerFor(rule));
    }
    return new CompositeExceptionHandler(builder.build());
  }
282374
def get_xml_parser(encoding=None):
    """"""
    parser = etree.ETCompatXMLParser(
        huge_tree=True,
        remove_comments=True,
        strip_cdata=False,
        remove_blank_text=True,
        resolve_entities=False,
        encoding=encoding
    )

    return parser
250117
private ExtractingResult parse(Result terms, boolean useForest) {
		if(terms==null || terms.size()==0){
			return new ExtractingResult() ;
		}

		if (useForest) {
			Graph graph = new Graph(terms);
			new UserDefineRecognition(TermUtil.InsertTermType.REPLACE,ruleIndex.getForest()).recognition(graph);
			graph.rmLittlePath();
			List<Term> result = new ArrayList<Term>();
			int length = graph.terms.length - 1;
			for (int i = 0; i < length; i++) {
				if (graph.terms[i] != null) {
					result.add(graph.terms[i]);
				}
			}
			terms = new Result(result) ;
		}


		List<ExtractingTask> tasks = new ArrayList<>();

		ExtractingResult result = new ExtractingResult();

		for (int i = 0; i < terms.size(); i++) {
			Term term = terms.get(i);

			Set<Rule> sets = new HashSet<>();

			Set<Rule> rules = ruleIndex.getRules(term.getName());
			if (rules != null) {
				sets.addAll(rules);
			}

			rules = ruleIndex.getRules(":" + term.getNatureStr());
			if (rules != null) {
				sets.addAll(rules);
			}

			rules = ruleIndex.getRules(":*");
			if (rules != null) {
				sets.addAll(rules);
			}

			for (Rule rule : sets) {
				tasks.add(new ExtractingTask(result, rule, i, terms));
			}
		}

		for (ExtractingTask task : tasks) {
			task.run();
		}

		return result;
	}
1314292
private void removeLinesFromXml(Rule rule, String sentenceToRemove, List<String> xmlLines) {
    List<Integer> linesToRemove = new ArrayList<>();
    String currentRuleId = null;
    Pattern pattern = Pattern.compile(".*id=[\"'](.*?)[\"'].*");
    String expectedSubId = ((AbstractPatternRule) rule).getSubId();
    int lineCount = 0;
    int subRuleCount = 0;
    int removedCount = 0;
    boolean inRuleGroup = false;
    for (String xmlLine : xmlLines) {
      if (xmlLine.contains("<rulegroup")) {
        subRuleCount = 0;
        inRuleGroup = true;
      } else if (xmlLine.contains("</rulegroup>")) {
        subRuleCount = 0;
        inRuleGroup = false;
      } else if ((xmlLine.contains("<rule ")||xmlLine.contains("<rule>")) && inRuleGroup) {
        subRuleCount++;
      }
      Matcher m = pattern.matcher(xmlLine);
      if (m.matches()) {
        currentRuleId = m.group(1);
      }
      if (!xmlLine.contains("correction=") && xmlLine.contains(sentenceToRemove + "</example>")) {
        if (currentRuleId != null && !currentRuleId.equals(rule.getId())) {
          lineCount++;
          continue;
        }
        if (!inRuleGroup) {
          subRuleCount = 1;
        }
        if (!expectedSubId.equals("0") && !expectedSubId.equals(String.valueOf(subRuleCount))) {
          lineCount++;
          continue;
        }
        linesToRemove.add(lineCount);
        break;
      }
      lineCount++;
    }
    Collections.reverse(linesToRemove); // start from end, as we need to remove items
    for (Integer s : linesToRemove) {
      xmlLines.remove(s.intValue());
      removedLinesCount++;
      removedCount++;
    }
    if (removedCount == 0) {
      System.err.println("No line removed: " + rule + "[" + expectedSubId + "]");
    }
  }
560102
private Selector parsePredicate(String predicate, String fullPath) 
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      tc.entry(cclass,
               "parsePredicate",
               "predicate: " + predicate); 

    Selector parsed = null;
    try
    {
      // Preprocess predicate for special characters
      String parserInput = preProcessForSpecials(predicate);
      
      // Attempt to parse predicate with "JMS" parser
      predicateParser =  MatchParserImpl.prime(predicateParser, parserInput, true);     
      parsed = predicateParser.getSelector(parserInput);
      if (parsed.getType() == Selector.INVALID)
      {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
          tc.debug(this,cclass, "parsePredicate", "Unable to parse predicate");           
        // reset the output to null
        parsed = null;
      }
      else
      {
        postProcessSelectorTree(parsed, fullPath);
      }
    }
    catch (Exception ex)
    {
      // No FFDC Code Needed.
      // In this case we will only trace the exception that we encountered.
      // It could be that the XPath parser is able to process this predicate
      // and that we've encountered a discrepancy between the syntax of an
      // expression supported by JMS and by XPath.
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        tc.debug(this,cclass, "parsePredicate", ex);   
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      tc.exit(this,cclass, "parsePredicate", parsed);     
    return parsed;
  }
447846
def fromxml(node):
        """"""
        if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
            node = parsexmlstring(node)
        assert node.tag.lower() == 'action'

        kwargs = {}
        args = []
        if 'id' in node.attrib:
            kwargs['id'] = node.attrib['id']
        elif 'name' in node.attrib:
            kwargs['name'] = node.attrib['name']
        elif 'description' in node.attrib:
            kwargs['description'] = node.attrib['description']
        elif 'method' in node.attrib:
            kwargs['method'] = node.attrib['method']
        elif 'mimetype' in node.attrib:
            kwargs['mimetype'] = node.attrib['mimetype']
        elif 'allowanonymous' in node.attrib:
            if node.attrib['allowanonymous'] == "yes":
                kwargs['allowanonymous'] = True

        found = False
        for subnode in node:
            if subnode.tag.lower() == 'parametercondition':
                kwargs[node.tag] = ParameterCondition.fromxml(subnode)
            elif subnode.tag in vars(clam.common.parameters):
                args.append(vars(clam.common.parameters)[subnode.tag].fromxml(subnode))
        if not found:
            raise Exception("No condition found in ParameterCondition!")
        return Action(*args, **kwargs)
1128874
private void extractXPathValidateExpressions(
            Element validateElement, Map<String, Object> validateXpathExpressions) {
        //check for xpath validation - old style with direct attribute
        String pathExpression = validateElement.getAttribute("path");
        if (StringUtils.hasText(pathExpression) && !JsonPathMessageValidationContext.isJsonPathExpression(pathExpression)) {
            //construct pathExpression with explicit result-type, like boolean:/TestMessage/Value
            if (validateElement.hasAttribute("result-type")) {
                pathExpression = validateElement.getAttribute("result-type") + ":" + pathExpression;
            }

            validateXpathExpressions.put(pathExpression, validateElement.getAttribute("value"));
        }

        //check for xpath validation elements - new style preferred
        List<?> xpathElements = DomUtils.getChildElementsByTagName(validateElement, "xpath");
        if (xpathElements.size() > 0) {
            for (Iterator<?> xpathIterator = xpathElements.iterator(); xpathIterator.hasNext();) {
                Element xpathElement = (Element) xpathIterator.next();
                String expression = xpathElement.getAttribute("expression");
                if (StringUtils.hasText(expression)) {
                    //construct expression with explicit result-type, like boolean:/TestMessage/Value
                    if (xpathElement.hasAttribute("result-type")) {
                        expression = xpathElement.getAttribute("result-type") + ":" + expression;
                    }

                    validateXpathExpressions.put(expression, xpathElement.getAttribute("value"));
                }
            }
        }
    }
1284362
function handleExprList (node, options) {
  const values = node.value.map((valueNode) => traverse(valueNode, options)).join(',')
  return `(${values})`
}
553020
function rule( context ) {
	/**
	* FUNCTION: validateLiteral( node )
	*	Validates a regular expression literal.
	*
	* @param {Node} node - AST node
	* @returns {Void}
	*/
	function validateLiteral( node ) {
		var token = context.getTokens( node )[ 0 ];
		if (
			token.type === 'RegularExpression' &&
			!safe( token.value )
		) {
			context.report( node, 'Unsafe regular expression' );
		}
	} // end FUNCTION validateLiteral()

	/**
	* FUNCTION: validateExpression( node )
	*	Validates a regular expression creating using the `RegExp` constructor.
	*
	* @param {Node} node - AST node
	* @returns {Void}
	*/
	function validateExpression( node ) {
		var args,
			len,
			re,
			i;

		if ( node.callee.name === 'RegExp' ) {
			len = node.arguments.length;
			args = new Array( node.arguments.length );
			for ( i = 0; i < len; i++ ) {
				// NOTE: we only support literals ATM. Otherwise, we may need to walk and implement an entire tree.
				if ( node.arguments[ i ].type !== 'Literal' ) {
					return;
				}
				args[ i ] = node.arguments[ i ].value;
			}
			re = RegExp.apply( null, args );
			if ( !safe( re ) ) {
				context.report( node, 'Unsafe regular expression' );
			}
		}
	} // end FUNCTION validateExpression()

	return {
		'Literal': validateLiteral,
		'NewExpression': validateExpression,
		'CallExpression': validateExpression
	};
}
1089516
private Document parseInputSourceWithFilter(InputSource s, XMLFilter f) throws JspException {
        try {
            XMLReader xr = XmlUtil.newXMLReader(entityResolver);
            //   (note that we overwrite the filter's parent.  this seems
            //    to be expected usage.  we could cache and reset the old
            //    parent, but you can't setParent(null), so this wouldn't
            //    be perfect.)
            f.setParent(xr);

            TransformerHandler th = XmlUtil.newTransformerHandler();
            Document o = XmlUtil.newEmptyDocument();
            th.setResult(new DOMResult(o));
            f.setContentHandler(th);

            f.parse(s);
            return o;
        } catch (IOException e) {
            throw new JspException(e);
        } catch (SAXException e) {
            throw new JspException(e);
        } catch (TransformerConfigurationException e) {
            throw new JspException(e);
        } catch (ParserConfigurationException e) {
            throw new JspException(e);
        }
    }
900910
@Nonnull
    private Rule rule( FormattableContainer parent, String selector, Operation params, Expression guard ) {
        Rule rule = new Rule( reader, parent, selector, params, guard );
        parseRule( rule );
        return rule;
    }
401168
List<MonitoringHandlerRun> extractRuleSections( File file, String fileContent, Properties params ) {

		// Find rules sections
		StringBuilder sb = new StringBuilder();
		List<String> sections = new ArrayList<String>();
		for( String s : Arrays.asList( fileContent.trim().split( "\n" ))) {
			s = s.trim();
			if( s.length() == 0
					|| s.startsWith( COMMENT_DELIMITER ))
				continue;

			if( s.toLowerCase().startsWith( RULE_BEGINNING )) {
				addSectionIfNotEmpty(sections, sb.toString());
				sb.setLength( 0 );
			}

			sb.append( Utils.expandTemplate(s, params) + "\n" );
		}

		addSectionIfNotEmpty(sections, sb.toString());

		// Now, prepare handler invocations
		List<MonitoringHandlerRun> result = new ArrayList<MonitoringHandlerRun> ();
		for( String s : sections ) {

			Matcher m = this.eventPattern.matcher( s );
			if( ! m.find())
				continue;

			s = s.substring( m.end()).trim();
			MonitoringHandlerRun bean = new MonitoringHandlerRun();
			bean.handlerName = m.group( 1 );
			bean.eventId = m.group( 2 );
			bean.rawRulesText = s;

			result.add( bean );
		}

		return result;
	}
947857
def parse(scanner, rules, scope = ParserScope.empty)
      rules.inherited_rule(rule_name).parse(scanner, rules, scope)
    end
454351
def fetch_and_parse(method, uri, params_prefix=None, **params):
    """"""
    doc = ElementTree.parse(fetch(method, uri, params_prefix, **params))
    return _parse(doc.getroot())
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
        )
398524
function() {
    var XML_GRAMMAR_SPEC = 'grammars/xml.peg';
    var NAMESPACE_SPEC = xml2js.opts.inputdir + '/namespace' + xml2js.opts.module + '.xml';
    var CLASS_SPEC = function(c) { return xml2js.opts.inputdir + '/' + c + '.xml'; }
    var TYPES_SPEC = xml2js.opts.inputdir + '/types_8h.xml';
    xml2js.MODULE = xml2js.opts.module;
    return Promise.join(createXmlParser(XML_GRAMMAR_SPEC),
                        xml2js.opts.typemaps ? initCustomPointerTypemaps(xml2js.opts.typemaps) : Promise.resolve(),
                        fs.readFileAsync(NAMESPACE_SPEC, 'utf8'),
                        fs.existsSync(TYPES_SPEC) ? fs.readFileAsync(TYPES_SPEC, 'utf8') : Promise.resolve(null),
                        function(xmlparser, ignore, xml, xml_types) {
      if (xml_types != null) {
        _.extend(xml2js.ENUMS, getEnums(xmlparser.parse(xml_types)[0], false));
        _.extend(xml2js.ENUMS_BY_GROUP, getEnums(xmlparser.parse(xml_types)[0], true));
      }
      var spec_c = xmlparser.parse(xml)[0];
      _.extend(xml2js.ENUMS, getEnums(spec_c, false));
      _.extend(xml2js.ENUMS_BY_GROUP, getEnums(spec_c, true));
      _.extend(xml2js.METHODS, getMethods(spec_c));
      _.each(getSubclassNames(spec_c), function(className) { xml2js.CLASSES[className] = {} });
      var parseClasses = _.map(getSubclasses(spec_c), function(c) {
        return fs.readFileAsync(CLASS_SPEC(c), 'utf8').then(function(xml) {
          try {
            var spec_c = xmlparser.parse(xml)[0];
            var className = getName(spec_c);
            _.extend(xml2js.CLASSES[className], {
              description: getDescription(spec_c),
              parent: getParent(spec_c, className),
              enums: getEnums(spec_c, false, className),
              enums_by_group: getEnums(spec_c, true, className),
              variables: getVariables(spec_c, className),
              methods: getMethods(spec_c, className)
            });
          } catch(e) {
            console.log(e.toString() + ': class ' + className + ' was not parsed correctly.');
          }
        });
      });
      var parseGroups = fs.readdirAsync(xml2js.opts.inputdir).then(function(files) {
        var groupxmlfiles = _.filter(files, function(fn) {
          return ((path.extname(fn) == '.xml') && (path.basename(fn).search(/^group/) != -1));
        });
        return Promise.all(_.map(groupxmlfiles, function(fn) {
          return fs.readFileAsync(xml2js.opts.inputdir + '/' + fn, 'utf8').then(function(xml) {
            var spec_c = xmlparser.parse(xml)[0];
            if (_.isEmpty(getSubmodules(spec_c))) {
              var group = getName(spec_c);
              var classes = getSubclassNames(spec_c);
              xml2js.CLASSGROUPS[group] = {
                description: getDescription(spec_c),
                classes: classes
              };
              _.each(classes, function(c) {
                if (_.has(xml2js.CLASSES, c)) {
                  xml2js.CLASSES[c].group = group;
                } else {
                  console.log('Warning: Group ' + group + ' has unknown class ' + c);
                }
              });
            }
          });
        }));
      });
      return Promise.all(parseClasses.concat(parseGroups));
    }).then(function() {
      if (!_.isEmpty(xml2js.CLASSGROUPS)) {
        // try to categorize ungrouped classes, if any
        var grouped = _.flatten(_.pluck(_.values(xml2js.CLASSGROUPS), 'classes'));
        var ungrouped = _.difference(_.keys(xml2js.CLASSES), grouped);
        _.each(ungrouped, function(c) {
          _.each(findUsage(c), function(group) {
            xml2js.CLASSGROUPS[group].classes.push(c);
          });
        });
        grouped = _.flatten(_.pluck(_.values(xml2js.CLASSGROUPS), 'classes'));
        ungrouped = _.difference(_.keys(xml2js.CLASSES), grouped);
        // try to categorize ungrouped enums, if any
        _.each(xml2js.ENUMS_BY_GROUP, function(enumGroupSpec, enumGroupName) {
          _.each(findUsage(enumGroupName, true), function(c) {
            xml2js.CLASSES[c].enums_by_group[enumGroupName] = enumGroupSpec;            
            _.each(enumGroupSpec.members, function(enumName) {
              xml2js.CLASSES[c].enums[enumName] = xml2js.ENUMS[enumName];
              delete xml2js.ENUMS[enumName];
            });
            delete xml2js.ENUMS_BY_GROUP[enumGroupName];
          });
        });
      }
    }).then(function() {
      if (xml2js.opts.custom && fs.existsSync(xml2js.opts.custom)) {
        return fs.readFileAsync(xml2js.opts.custom, 'utf8').then(function(custom) {
          try {
            customizeMethods(JSON.parse(custom));
          } catch(e) {
            console.log('invalid custom.json, ignored. ' + e.toString());
          }
        });
      } else {
        console.log(xml2js.opts.custom ? ('Error: No such customization file exists: ' + xml2js.opts.custom) : 'No customizations given.');
      }
    }).then(function() {
      generateCustomPointerClasses();       
      validateMethods();
      validateVars();
      return _.pick(xml2js, 'MODULE', 'ENUMS', 'ENUMS_BY_GROUP', 'METHODS', 'CLASSES', 'CLASSGROUPS');
    });
  }
1322770
function parse(xml, processNamespaces, angularSyntax) {
    var doc = new XDocument();
    var errors = [];
    var elementStack = [];
    var currentContainer = function () { return elementStack.length > 0 ? elementStack[elementStack.length - 1] : doc; };
    var xParser = new Xml.XmlParser(function (e) {
        var c = currentContainer();
        if (e.eventType === Xml.ParserEventType.StartElement) {
            var newElement = new XElement(e.elementName);
            newElement.add(e.data);
            var attribs = getOwnProperties(e.attributes);
            if (!TypeUtils.isNullOrUndefined(attribs)) {
                for (var p in attribs) {
                    var a = new XAttribute(p);
                    a.value = attribs[p];
                    newElement.add(a);
                }
            }
            currentContainer().add(newElement);
            elementStack.push(newElement);
        }
        else if (e.eventType === Xml.ParserEventType.Text) {
            var newText = new XText();
            newText.value = e.data;
            currentContainer().add(newText);
        }
        else if (e.eventType === Xml.ParserEventType.CDATA) {
            var newCData = new XCData();
            newCData.value = e.data;
            currentContainer().add(newCData);
        }
        else if (e.eventType === Xml.ParserEventType.Comment) {
            var newComment = new XComment();
            newComment.value = e.data;
            currentContainer().add(newComment);
        }
        else if (e.eventType === Xml.ParserEventType.EndElement) {
            elementStack.pop();
        }
    }, function (error, position) {
        errors.push([error, position]);
    }, processNamespaces, angularSyntax);
    xParser.parse(xml);
    if (errors.length > 0) {
        // collect errors and throw
        var exceptionMsg = 'XML parse error:';
        for (var i = 0; i < errors.length; i++) {
            var err = errors[i][0];
            var pos = errors[i][1];
            exceptionMsg += "\n(" + pos.column + "," + pos.line + "): [" + err.name + "] " + err.message;
        }
        throw exceptionMsg;
    }
    return doc;
}