Here you can find the source of validateXPath(final Document doc, final String xpathExpression)
Parameter | Description |
---|---|
doc | The XML document |
xpathExpression | The XPath expression |
public static String validateXPath(final Document doc, final String xpathExpression)
//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$ } } }