Java XPath Validate validateXPathExpression(String xpathExpression)

Here you can find the source of validateXPathExpression(String xpathExpression)

Description

Validates a XPath expression.

License

Open Source License

Parameter

Parameter Description
xpathExpression the XPath expression to validate

Return

null if the expression is correct, an error message otherwise

Declaration

public static String validateXPathExpression(String xpathExpression) 

Method Source Code

//package com.java2s;
/******************************************************************************
 * Copyright (c) 2009-2013, Linagora/*from  w  ww. j a  va2  s .  co m*/
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *       Linagora - initial API and implementation
 *******************************************************************************/

import javax.xml.xpath.XPath;

import javax.xml.xpath.XPathFactory;

public class Main {
    /**
     * Not sensitive to name spaces (for instance, but not sure either it will be one day).
     */
    private static final XPath X_PATH = XPathFactory.newInstance().newXPath();

    /**
     * Validates a XPath expression.
     * @param xpathExpression the XPath expression to validate
     * @return null if the expression is correct, an error message otherwise
     */
    public static String validateXPathExpression(String xpathExpression) {

        String msg = null;
        try {
            X_PATH.compile(xpathExpression);

        } catch (Exception e) {
            String cause = null;
            if (e.getCause() != null)
                e.getCause().getMessage();
            else
                cause = e.getMessage();

            cause = cause == null ? "" : " " + cause;
            msg = "Invalid XPath expression." + cause;
        }

        return msg;
    }
}

Related

  1. validateXPath(final Document doc, final String xpathExpression)
  2. validateXPath(String path)
  3. validateXPath(String xml, String... tests)