Java XPath scan file looking for a word

Viewed 40

Im building an application that will taka a word from user and then scan file using XPath returning true or false depending on wheather the word was found in that file or not.

I have build following class that implements XPath, but i am either missunderstanding how it should work or there is something wrong with my code. Can anyone explain to me how to use Xpath to make full file search?

public XPath() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
        FileInputStream fileIS = new FileInputStream("text.xml");
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document xmlDocument = builder.parse(fileIS);
        XPathFactory xPathfactory = XPathFactory.newInstance();
        javax.xml.xpath.XPath xPath = xPathfactory.newXPath();
        XPathExpression expr = xPath.compile("//text()[contains(.,'java')]");
        System.out.println(expr.evaluate(xmlDocument, XPathConstants.NODESET));
    }

And the xml file i am currently testing on.

<?xml version="1.0"?>
<Tutorials>
    <Tutorial tutId="01" type="java">
        <title>Guava</title>
        <description>Introduction to Guava</description>
        <date>04/04/2016</date>
        <author>GuavaAuthor</author>
    </Tutorial>
    <Tutorial tutId="02" type="java">
        <title>XML</title>
        <description>Introduction to XPath</description>
        <date>04/05/2016</date>
        <author>XMLAuthor</author>
    </Tutorial>
</Tutorials>

Found the solution, i was missing correct display of the found entries and as someone pointed out in comment 'java' is in arguments and i want to scan only text fields so it would be never found, after adding following code and changing the word my app will look for, application works

Object result = expr.evaluate(xmlDocument, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue());
        }
1 Answers

Your XPath is searching the text() nodes, but the word java appears in the @type attribute (which is not a text() node).

If you want to search for the word in both text() and @* then you could use a union | operator and check for either/both containing that word:

//text()[contains(. ,'java')] | //@*[contains(., 'java')]

But you might also want to scan comment() and processing-instruction(), so could generically match on node() and then in the predicate test:

//node()[contains(. ,'java')] | //@*[contains(., 'java')]

With XPath 2.0 or greater, you could use:

//node()[(.|@*)[contains(., 'java')]]
Related