Java XPath Validate validateXPath(final Document doc, final String xpathExpression)

Here you can find the source of validateXPath(final Document doc, final String xpathExpression)

Description

Validates the XPath expression entered by the user in a wizard.

License

Open Source License

Parameter

Parameter Description
doc The XML document
xpathExpression The XPath expression

Return

single, multiple, none or attribute depending on the entered XPath expression

Declaration

public static String validateXPath(final Document doc, final String xpathExpression) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009 Dominik Schadow - http://www.xml-sicherheit.de 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: Dominik Schadow - initial API and implementation
 *******************************************************************************/

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**/* ww w. jav a  2s  .c  o  m*/
     * Validates the XPath expression entered by the user in a wizard. The user can only continue
     * with the entered XPath if <i>single</i> is returned.
     *
     * @param doc The XML document
     * @param xpathExpression The XPath expression
     * @return <i>single</i>, <i>multiple</i>, <i>none</i> or <i>attribute</i> depending on the
     *         entered XPath expression
     */
    public static String validateXPath(final Document doc, final String xpathExpression) {
        try {
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList) xpath.evaluate(xpathExpression, doc, XPathConstants.NODESET);

            if (nodes.getLength() == 1) {
                if (nodes.item(0).getNodeType() == Node.ATTRIBUTE_NODE) {
                    return "attribute"; //$NON-NLS-1$
                } else if (nodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                    return "single"; //$NON-NLS-1$
                }
            } else if (nodes.getLength() > 1) {
                return "multiple"; //$NON-NLS-1$
            }

            return "none"; //$NON-NLS-1$
        } catch (Exception ex) {
            return "none"; //$NON-NLS-1$
        }
    }
}

Related

  1. validateXPath(String path)
  2. validateXPath(String xml, String... tests)
  3. validateXPathExpression(String xpathExpression)