Search in sources :

Example 1 with XpathParserException

use of cn.wanghaomiao.xpath.exception.XpathParserException in project JsoupXpath by zhegexiaohuozi.

the class XpathProcessor method visitAdditiveExpr.

@Override
public XValue visitAdditiveExpr(XpathParser.AdditiveExprContext ctx) {
    List<XpathParser.MultiplicativeExprContext> multiplicativeExprContexts = ctx.multiplicativeExpr();
    if (multiplicativeExprContexts.size() == 1) {
        return visit(multiplicativeExprContexts.get(0));
    } else {
        Double res = visit(multiplicativeExprContexts.get(0)).asDouble();
        String op = null;
        for (int i = 1; i < ctx.getChildCount(); i++) {
            ParseTree chiCtx = ctx.getChild(i);
            if (chiCtx instanceof XpathParser.MultiplicativeExprContext) {
                XValue next = visit(chiCtx);
                if ("+".equals(op)) {
                    res += next.asDouble();
                } else if ("-".equals(op)) {
                    res -= next.asDouble();
                } else {
                    throw new XpathParserException("syntax error, " + ctx.getText());
                }
            } else {
                op = chiCtx.getText();
            }
        }
        return XValue.create(res);
    }
}
Also used : XpathParserException(cn.wanghaomiao.xpath.exception.XpathParserException) ParseTree(org.antlr.v4.runtime.tree.ParseTree)

Example 2 with XpathParserException

use of cn.wanghaomiao.xpath.exception.XpathParserException in project JsoupXpath by zhegexiaohuozi.

the class XpathProcessor method visitPredicate.

@Override
public XValue visitPredicate(XpathParser.PredicateContext ctx) {
    Elements newContext = new Elements();
    for (int i = 0; i < currentScope().context().size(); i++) {
        Element e = currentScope().context().get(i);
        scopeStack.push(Scope.create(e).setParent(currentScope()));
        XValue exprVal = visit(ctx.expr());
        scopeStack.pop();
        if (exprVal.isNumber()) {
            long index = exprVal.asLong();
            if (index < 0) {
                index = currentScope().context().size() + index + 1;
            }
            if (index == i + 1) {
                newContext.add(e);
            }
        } else if (exprVal.isBoolean()) {
            if (exprVal.asBoolean()) {
                newContext.add(e);
            }
        } else {
            throw new XpathParserException("unknown expr val:" + exprVal);
        }
    }
    return XValue.create(newContext);
}
Also used : Element(org.jsoup.nodes.Element) Elements(org.jsoup.select.Elements) XpathParserException(cn.wanghaomiao.xpath.exception.XpathParserException)

Aggregations

XpathParserException (cn.wanghaomiao.xpath.exception.XpathParserException)2 ParseTree (org.antlr.v4.runtime.tree.ParseTree)1 Element (org.jsoup.nodes.Element)1 Elements (org.jsoup.select.Elements)1