Ramesh
Ramesh

Reputation: 2337

Getting an xpath value of an node with out iterating in java

I have an xml

<?xml version="1.0" encoding="UTF-8"?>
<information>
  <person id="1">
  <name>Deep</name>
  <age>34</age>
  <gender>Male</gender>
  </person>

 <person id="2">
  <name>Kumar</name>
  <age>24</age>
  <gender>Male</gender>
  </person>

  <person id="3">
  <name>Deepali</name>
  <age>19</age>
  <gender>Female</gender>
  </person>

  <!-- more persons... -->
</information>
DocumentBuilderFactory domFactory = DocumentBuilderFactory
                .newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse("persons.xml");
        XPath xpath = XPathFactory.newInstance().newXPath();
        // XPath Query for showing all nodes value
        XPathExpression expr = xpath.compile("//information/person[0]/name/text()");

        Object result = expr.evaluate(doc, XPathConstants.NODE);
        Node node = (Node) result;
        System.out.println(node.getNodeValue());

And i need to extract the name of the first person i tried the above code it gives exception can any one help me in this,

UPDATED Exception

Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to javax.xml.soap.Node
    at xml.main(xml.java:33)

UPDATED ANSWER

XPathExpression expr = xpath.compile("//information/person[1]/name");

        String str = (String) expr.evaluate(doc, XPathConstants.STRING);

        System.out.println(str);

Upvotes: 0

Views: 2139

Answers (2)

JWiley
JWiley

Reputation: 3209

XPath indexing starts at base 1, not 0 as most would think, so person[0] won't return anything. Change your XPath to //information/person[1]/name/text() You could also specify the position to avoid simply using static numbers altogether: //information/person[position()=1]/name/text()

or //information/person[@id='1']/name/text() if you need it by id.

Upvotes: 1

Ramesh
Ramesh

Reputation: 2337

XPathExpression expr = xpath.compile("//information/person[1]/name");

    String str = (String) expr.evaluate(doc, XPathConstants.STRING);

    System.out.println(str);

Upvotes: 1

Related Questions