Java XPath Select getValueByXPath(Document document, String xpath)

Here you can find the source of getValueByXPath(Document document, String xpath)

Description

Get a value by xpath.

License

Open Source License

Parameter

Parameter Description
document xml document to apply xpath to.
xpath the xpath to get the value from.

Return

value from the xpath, or an empty string.

Declaration

static String getValueByXPath(Document document, String xpath) 

Method Source Code


//package com.java2s;
/*// ww  w .  jav a 2  s .com
 * Knicker is Copyright 2010-2012 by Jeremy Brooks
 *
 * This file is part of Knicker.
 *
 * Knicker is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Knicker 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Knicker.  If not, see <http://www.gnu.org/licenses/>.
 */

import org.w3c.dom.Document;

import javax.xml.xpath.XPathFactory;

public class Main {
    private static XPathFactory xPathFactory;

    /**
     * Get a value by xpath.
     * <p/>
     * This method will return an empty string if there are any errors, such
     * as an invalid xpath or an invalid document object.
     *
     * @param document xml document to apply xpath to.
     * @param xpath    the xpath to get the value from.
     * @return value from the xpath, or an empty string.
     */
    static String getValueByXPath(Document document, String xpath) {
        String value = "";
        try {
            value = xPathFactory.newXPath().evaluate(xpath, document).trim();
        } catch (Exception e) {
            // ignore; will return empty string
        }

        return value;
    }
}

Related

  1. getValueByXPathAsInt(Document document, String xpath)
  2. getValueFromXPath(Document document, String xpathString)
  3. getXmlElements(Document inXml, String xpath)
  4. selectElements(Element element, String xpathExpression)