0

I'm beginner in xpath for java. I want to get all the nodes that contain specific text, so I tried:

keyword = "employee//[contains(text()," + inputText + ")]";

NodeList nodes = (NodeList) xpath.evaluate(keyword, doc, XPathConstants.NODESET);

after that the result is all the employee elements even they do not have the certain text in it!

Please, help me how I can get only the employee elements that have the text?

Thank you,

2
  • What is your input, and what is the output you currently get from the input with above code? Commented Feb 18, 2018 at 17:20
  • Your XPath is malformed, or your typed it in your question wrong. You've not included the XML being queried. Your question could have been closed for lacking a minimal reproducible example, but it's likely that the underlying issue will be addressed by the answer in the duplicate link. If not, improve this question and request that it be reopened. Thanks. Commented Feb 18, 2018 at 18:33

1 Answer 1

0

Hello I tried looking for all employees whose name was Guido. The code is the following. It works for me.

    String name="Guido";
    FileInputStream fileIS = new FileInputStream("C:/Users/Maxi/workspace/ProyectoIteraciones/src/com/proyecto/init/Employees.xml");
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(fileIS);
    XPath xPath = XPathFactory.newInstance().newXPath();        
    String expression = "//Employee/Name[contains(.,'"+name+"')]";      
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
    System.out.println("El resultado es "+nodeList.item(0).getTextContent());

enter image description here

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

1 Comment

It works, thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.