2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.ecovacs.internal.api.util;
15 import java.io.StringReader;
16 import java.util.Optional;
18 import javax.xml.xpath.XPath;
19 import javax.xml.xpath.XPathConstants;
20 import javax.xml.xpath.XPathExpressionException;
21 import javax.xml.xpath.XPathFactory;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.w3c.dom.Node;
26 import org.w3c.dom.NodeList;
27 import org.xml.sax.InputSource;
30 * @author Danny Baumann - Initial contribution
33 public class XPathUtils {
34 private static @Nullable XPathFactory factory;
36 public static Node getFirstXPathMatch(String xml, String xpathExpression) throws DataParsingException {
37 NodeList nodes = getXPathMatches(xml, xpathExpression);
38 if (nodes.getLength() == 0) {
39 throw new DataParsingException("No nodes matching expression " + xpathExpression + " in XML " + xml);
44 public static Optional<Node> getFirstXPathMatchOpt(String xml, String xpathExpression) throws DataParsingException {
45 NodeList nodes = getXPathMatches(xml, xpathExpression);
46 return nodes.getLength() == 0 ? Optional.empty() : Optional.of(nodes.item(0));
49 public static NodeList getXPathMatches(String xml, String xpathExpression) throws DataParsingException {
51 InputSource source = new InputSource(new StringReader(xml));
52 return (NodeList) newXPath().evaluate(xpathExpression, source, XPathConstants.NODESET);
53 } catch (XPathExpressionException e) {
54 throw new DataParsingException(e);
58 @SuppressWarnings("null") // null annotations don't recognize FACTORY can not be null in return statement
59 private static XPath newXPath() {
60 synchronized (XPathUtils.class) {
61 if (factory == null) {
62 factory = XPathFactory.newInstance();
64 return factory.newXPath();