Java tutorial
//package com.java2s; /* * Copyright 2010-2013, CloudBees Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.annotation.Nonnull; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; public class Main { private final static XPath xpath = XPathFactory.newInstance().newXPath(); /** * Returns the unique XML element matching the given {@code xpathExpression} * * @param document * @param xpathExpression xpath expression to find the element * @return the matching element * @throws RuntimeException 0 or more than 1 matching element found */ @Nonnull public static Element getUniqueElement(@Nonnull Document document, @Nonnull String xpathExpression) throws RuntimeException { return getUniqueElement((Node) document, xpathExpression); } /** * Returns the unique XML element matching the given {@code xpathExpression} * * @param element * @param xpathExpression xpath expression to find the element * @return the matching element * @throws RuntimeException 0 or more than 1 matching element found */ @Nonnull public static Element getUniqueElement(@Nonnull Element element, @Nonnull String xpathExpression) { return getUniqueElement((Node) element, xpathExpression); } /** * Returns the unique XML element matching the given {@code xpathExpression} * * @param node * @param xpathExpression xpath expression to find the node * @return the matching node * @throws RuntimeException 0 or more than 1 matching element found */ @Nonnull public static Element getUniqueElement(@Nonnull Node node, @Nonnull String xpathExpression) { try { NodeList nl = (NodeList) xpath.compile(xpathExpression).evaluate(node, XPathConstants.NODESET); if (nl.getLength() == 0 || nl.getLength() > 1) { throw new RuntimeException("More or less (" + nl.getLength() + ") than 1 node found for expression: " + xpathExpression); } return (Element) nl.item(0); } catch (Exception e) { throw new RuntimeException("Exception evaluating xpath '" + xpathExpression + "' on " + node, e); } } }