2

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

2
  • Are there any namespaces involved? Show the code that loaded the XML document. Commented Nov 20, 2013 at 6:07
  • Let's start with the fact that your example XML is not formatted correctly... Commented Nov 20, 2013 at 6:22

1 Answer 1

5

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...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.