Java XPath Find querySingle(Node node, String xpathQuery, final String filePath)

Here you can find the source of querySingle(Node node, String xpathQuery, final String filePath)

Description

query Single

License

Open Source License

Declaration

public static String querySingle(Node node, String xpathQuery, final String filePath) 

Method Source Code

//package com.java2s;
/*// www.j av  a2s.  c o  m
 * JBoss, Home of Professional Open Source.
 * Copyright 2007, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 * 
 */

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

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

public class Main {
    private static XPathFactory xPathFactory = XPathFactory.newInstance();

    public static String querySingle(Node node, String xpathQuery, final String filePath) {

        NodeList list = query(node, xpathQuery, filePath);
        int count = list.getLength();

        if (count > 1)
            throw new RuntimeException(
                    "query " + xpathQuery + " returned " + list.getLength() + " results. Should have been one.");

        return count == 1 ? list.item(0).getTextContent() : null;
    }

    public static NodeList query(Node node, String xpathQuery, final String filePath) {

        if (node == null)
            throw new NullPointerException("document was null " + filePath);

        XPath xpath = xPathFactory.newXPath();

        try {

            return (NodeList) xpath.evaluate(xpathQuery, node, XPathConstants.NODESET);

        } catch (Exception e) {
            throw new RuntimeException("Could not run XPath query '" + xpathQuery + "' on document " + filePath);
        }

    }
}

Related

  1. findNodeByXpath(String xpathExpression, String fileName)
  2. findNodeByXPath(String xPathString, Object source)
  3. findNodes(final Node node, final String expression)
  4. findNodesByXPath(Node contextNode, String expression)
  5. query(Node context, String query)