How to get elements from XPath in Java

kskaradzinski picture kskaradzinski · May 17, 2011 · Viewed 9.9k times · Source

I want to get data from an XPath query:

Element location = (Element) doc.query("//location[location_name='"+ locationName +"']/*").get(0).getDocument().getRootElement();
System.out.println(location.toXML());

Element loc = location.getFirstChildElement("location");
System.out.println(loc.getFirstChildElement("location_name").getValue());

However, no matter what I choose, I always get 1 node (because of .get(0)). I don't know how to select the node which was selected by query.

I found that I should cast the node to Element, (XOM getting attribute from Node?) but the link only shows how to select the first node.

Answer

orangepips picture orangepips · Jun 7, 2011

Call getParent() on the first element in the result:

Builder parse = new Builder();
Document xml = parse.build("/var/www/JAVA/toForum.xml");

System.out.println(xml.query("//location[@id=83]/*").get(0).getParent().toXML());

Produces the following output:

<location id="83">
  <location_name>name</location_name>
  <company_name>company a</company_name>
  <machines>
    <machine id="12">A</machine>
    <machine id="312">B</machine>
  </machines>
</location>