1

This is my xml and i wanted to fetch value of Id tag '4654'

<Entity>
       <acc>
            <id>4654</id>
            <name>abc</name>
       </acc>
       <acc>
            <id>5465</id>
            <name>xyz</name>
       </acc>

I am using this code to retrieve the Id value

       DocumentBuilderFactory factory =    DocumentBuilderFactory.newInstance();
       DocumentBuilder builder = factory.newDocumentBuilder();
       Document document = builder.parse(new InputSource(new StringReader(xml))); 
       XPath xPath = XPathFactory.newInstance().newXPath();
       NodeList  node = (NodeList) xPath.evaluate("/Entity/acc/id/text()", document, XPathConstants.NODE);
       System.out.println("node length:"+node.getLength());
       System.out.println("node value:"+ node.item(0).getNodeValue());
       return node.item(0).getNodeValue();

Output returns null

Any help would be appreciated

1
  • which output is null? Commented Jul 12, 2017 at 20:21

1 Answer 1

3

You need to use XPathConstants.NODESET instead of XPathConstants.NODE

or you can keep it as XPathConstants.NODE and change the evaluate to return Node

Node node = (Node) xPath.evaluate("/Entity/acc/id/text()", document, XPathConstants.NODE);

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.