select Single Node from XML String using XPath expression - Java XML

Java examples for XML:XPath

Description

select Single Node from XML String using XPath expression

Demo Code

/*// ww  w . j  av a2s  .c  om
 * Copyright (c) Shanghai Zhiping Technology Co.,Limited
 * Author: Binhua Liu
 * Web Site: www.vowei.com
 * License: GPL v3 (http://www.gnu.org/copyleft/gpl.html)
 */
//package com.java2s;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Node;

public class Main {
    public static void main(String[] argv) throws Exception {
        String express = "java2s.com";
        Object source = "java2s.com";
        System.out.println(selectSingleNode(express, source));
    }

    public static Node selectSingleNode(String express, Object source) {
        Node result = null;
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        try {
            result = (Node) xpath.evaluate(express, source,
                    XPathConstants.NODE);
        } catch (XPathExpressionException e) {
            // TODO e.printStackTrace();
        }

        return result;
    }
}

Related Tutorials