Evaluate XML by XPath and return bool - Java XML

Java examples for XML:XPath

Description

Evaluate XML by XPath and return bool

Demo Code


//package com.java2s;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Node;

public class Main {
    static private XPath xpath;

    static public Boolean bool(Node context, String expression) {
        String value = string(context, expression);
        if (value != null)
            return !value.equals("0");
        else/*from   w  w  w  .  j  ava 2  s . c om*/
            return null;
    }

    static public boolean bool(Node context, String expression,
            boolean defaultValue) {
        String value = string(context, expression);
        if (value == null)
            return defaultValue;
        return !value.equals("0");
    }

    static public String string(Node context, String expression) {
        try {
            String result = (String) xpath.evaluate(expression, context,
                    XPathConstants.STRING);
            if (result == null || result.length() == 0)
                return null;
            else
                return result;
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
            throw new RuntimeException("invalid xpath expresion used");
        }
    }

    static public String string(Node context, String expression,
            String defaultValue) {
        try {
            String result = (String) xpath.evaluate(expression, context,
                    XPathConstants.STRING);
            if (result == null || result.length() == 0)
                return defaultValue;
            else
                return result;
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
            throw new RuntimeException("invalid xpath expresion used");
        }
    }
}

Related Tutorials