评估不包含xml标记的XPath查询

时间:2014-02-19 14:51:25

标签: java xml xpath

我需要知道,在java中使用XPath,我是否可以在查询结果中获取XML片段。我会更好地解释,我正在使用这个简单的XML文件:

<bookshelf>
    <shelf>
        <book>
            <author>J.R.R. Tolkien</author>
            <title>The Lord of the Rings</title>
        </book>
    </shelf>
</bookshelf>

我必须评估的查询XPath是:/bookshelf/shelf/book

我需要找到一种方法来保持XPATH响应中的XML标记获得如下结果:

<author>J.R.R. Tolkien</author>
<title>The Lord of the Rings</title>

有可能吗?

1 个答案:

答案 0 :(得分:0)

是的,可以使用标准的java XPath API:

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

import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Snippet {
    public static void main(String[] args) throws Exception {
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xpath.evaluate("/bookshelf/shelf/book/*", 
                new InputSource(Snippet.class.getResourceAsStream("/books.xml")),
                XPathConstants.NODESET);
        System.out.println("First  node: " + nodes.item(0));
        System.out.println("Second node: " + nodes.item(1));
    }
}

您可以要求XPath API返回节点列表,单个节点,字符串等。使用evaluate方法的最后一个参数:请参阅XPathConstants class。