XPath to select all nodes in document with specified name in java

10,676

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>

Using the following code...

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();
        }
    }

}

I was able to get it to output...

Found 3 results

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

Share:
10,676
Spark-Beginner
Author by

Spark-Beginner

I appreciate all edits to my answers, and promptly approve most edit suggestions.

Updated on June 05, 2022

Comments

  • Spark-Beginner
    Spark-Beginner almost 2 years

    Sample XML

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

    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