Get number from XML Element by XPath expression - Java XML

Java examples for XML:XPath

Description

Get number from XML Element by XPath expression

Demo Code


//package com.java2s;

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

import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {
    static private XPath xpath;

    public static Double number(Element context, String expression) {
        String value = string(context, expression);
        if (value == null)
            return null;
        return Double.parseDouble(value);
    }//from  www . j a  va 2  s .  c om

    public static Double number(Element context, String expression,
            double defaultValue) {
        String value = string(context, expression);
        if (value == null)
            return defaultValue;
        return Double.parseDouble(value);
    }

    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