Java XPath Get getStringValue(Object doc, XPathExpression path)

Here you can find the source of getStringValue(Object doc, XPathExpression path)

Description

get String Value

License

Open Source License

Declaration

public static String getStringValue(Object doc, XPathExpression path)
            throws XPathExpressionException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.HashMap;

import java.util.Map;

import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;

import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

public class Main {
    private static ThreadLocal<Map<String, XPathExpression>> sCache = new ThreadLocal<Map<String, XPathExpression>>();
    private static XPathFactory sFactory = XPathFactory.newInstance();

    public static String getStringValue(Object doc, XPathExpression path)
            throws XPathExpressionException {
        return path.evaluate(doc);
    }// www  . j a va 2s . c  o m

    public static String getStringValue(Object doc, NamespaceContext ctx,
            String path) throws XPathExpressionException {
        return getStringValue(doc, getXPath(path, ctx));
    }

    public static String getStringValue(Object doc, String path)
            throws XPathExpressionException {
        return getStringValue(doc, null, path);
    }

    public static XPathExpression getXPath(String exp)
            throws XPathExpressionException {
        Map<String, XPathExpression> cache = getCache();
        if (!cache.containsKey(exp)) {
            cache.put(exp, sFactory.newXPath().compile(exp));
        }
        return cache.get(exp);
    }

    public static XPathExpression getXPath(String exp, NamespaceContext ctx)
            throws XPathExpressionException {
        if (ctx == null) {
            return getXPath(exp);
        }
        XPath mRetVal = sFactory.newXPath();
        mRetVal.setNamespaceContext(ctx);
        return mRetVal.compile(exp);
    }

    private static Map<String, XPathExpression> getCache() {
        Map<String, XPathExpression> mRetVal = sCache.get();
        if (mRetVal == null) {
            mRetVal = new HashMap<String, XPathExpression>();
            sCache.set(mRetVal);
        }
        return mRetVal;
    }
}

Related

  1. getStrFromNode(Node xpathnode)
  2. getString(final String xPath, final Object item)
  3. getString(Node node, XPathExpression expr)
  4. getStringByXPath(String xml, String xpathStr)
  5. getStringValue(Node node, XPathExpression expression)
  6. getStringValue(String targetDoc, String xpathExp, String encoding)
  7. getStringValueByXPath(Node node, String xPath)
  8. getText(String xPathExpression, Node node)
  9. getTextNodes(Node contextNode, String xPath)