XPath选择java中具有指定名称的文档中的所有节点

时间:2013-11-20 06:04:44

标签: java xml xslt xpath

示例XML

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

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

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

但是这段代码没有选择任何板球节点。请建议

1 个答案:

答案 0 :(得分:4)

基于您的“更正”示例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形成错误而且你忽略了由于它而抛出的任何异常......