XPath在java中选择具有指定名称的文档中的所有节点 [英] XPath to select all nodes in document with specified name in java

查看:23
本文介绍了XPath在java中选择具有指定名称的文档中的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<Games>
    <Indoor>
        <TT></TT>
        <Chess></chess>
         <cricket>asd</cricket>
        <ComputerGame>
                  <cricket>asd</cricket>
        </ComputerGame>
    </Indore>
    <Outdoor>
         <Football></Football>
         <cricket>asd</cricket>
    </outdoor>
</Games>

我想选择所有节点名称为 cricket 的节点.为此我是:

I want to select all the node with node name cricket. for this I am :

NodeList nodeList= (NodeList)xpath.compile("//cricket").evaluate(xmlDocument,XPathConstants.NODESET);

但是这个代码没有选择任何板球节点.请推荐

But this code doesnt select any cricket node. PLEASE SUGGEST

推荐答案

基于您更正"的示例 XML...

Based on your "corrected" example XML...

<Games>
    <Indoor>
        <TT></TT>
        <Chess>
        </Chess>
        <cricket>asd</cricket>
        <ComputerGame>
            <cricket>asd</cricket>
        </ComputerGame>
    </Indoor>
    <Outdoors>
        <Football></Football>
        <cricket>asd</cricket>
    </Outdoors>
</Games>

使用以下代码...

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class TestXPath101 {

    public static void main(String[] args) {
        try {
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("Test.xml"));
            XPath xPath = XPathFactory.newInstance().newXPath();
            XPathExpression exp = xPath.compile("//cricket");
            NodeList nl = (NodeList)exp.evaluate(doc, XPathConstants.NODESET);
            System.out.println("Found " + nl.getLength() + " results");
        } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
            ex.printStackTrace();
        }
    }

}

我能够让它输出...

Found 3 results

我会怀疑"您的 XML 格式错误,并且您忽略了因此引发的任何异常...

I would "suspect" that you XML is ill formed and you are ignoring any exceptions that are being thrown because of it...

这篇关于XPath在java中选择具有指定名称的文档中的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆