Java XPath Create getXpathExpressionValue(Object xprContext, String xpExpression)

Here you can find the source of getXpathExpressionValue(Object xprContext, String xpExpression)

Description

get Xpath Expression Value

License

Open Source License

Declaration

public static String getXpathExpressionValue(Object xprContext, String xpExpression)
            throws XPathExpressionException 

Method Source Code


//package com.java2s;
/*/*from  w  ww .  j  a v a2s  . com*/
    
Copyright (c) 2009-2011, AOL Inc.
All rights reserved.
    
This code is licensed under a BSD license.
    
Howard Uman
    
*/

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Node;

public class Main {
    public static String getXpathExpressionValue(Object xprContext, String xpExpression)
            throws XPathExpressionException {
        XPath xpath = XPathFactory.newInstance().newXPath();

        XPathExpression xpe = xpath.compile(xpExpression);
        Node valueNode = (Node) xpe.evaluate(xprContext, XPathConstants.NODE);
        String value = null;
        if (valueNode != null)
            value = valueNode.getNodeValue();
        if (value != null) {
            // if the node is a text node - then we trim and (potentially) look for CDATA
            if (valueNode.getNodeType() == Node.TEXT_NODE) {
                value = value.trim();

                // look for CDATA if we got nothing (stupid whitespace)
                if (value.length() == 0) {
                    Node siblingForCDATA = valueNode.getNextSibling();
                    if (siblingForCDATA.getNodeType() == Node.CDATA_SECTION_NODE) {
                        value = siblingForCDATA.getNodeValue();
                    }
                }
            }
        }

        return value;
    }
}

Related

  1. getXPathExpression(String path)
  2. getXPathExpression(String xpath, NamespaceContext namespaceContext)
  3. getXPathExpression(String xpathStr)
  4. getXPathExpression(String xPathString)
  5. getXpathExpressionNode(Object xprContext, String xpExpression)
  6. getXPathExprFromNode(Node node)
  7. getXPathExprFromNode(Node node)
  8. getXPathFactory()
  9. getXPathFactory()