select Nodes from XML String by XPath expression - Java XML

Java examples for XML:XPath

Description

select Nodes from XML String by XPath expression

Demo Code

/*/*from   ww  w  .  j  a  v  a  2  s .c o  m*/
 * 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.NodeList;

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

    public static NodeList selectNodes(String express, Object source) {
        NodeList result = null;
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        try {
            result = (NodeList) xpath.evaluate(express, source,
                    XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }

        return result;
    }
}

Related Tutorials