How to get elements from XPath in Java

10,129

Solution 1

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>

Solution 2

The call you make to getDocument() is returning the entirety of the XML document.

The call to query() returns a Nodes object directly containing references to the nodes that you are after.

If you change to

Element location = (Element)doc.query(
            "//location[location_name='"+ locationName +"']/*").get(0);

System.out.println(location.getAttribute("location_name").getValue());

it should be ok

EDIT (by extraneon)

Some extra explanation not worthy of an answer by itself: By doing

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

you search through the tree and get the requested node. But then you call getDocument().getRootNode() on the element you want, which will give you the uppermost node of the document.

The above query can thus be simplified to:

Element location = (Element)doc.getRootElement();

which is not wahat you intended.

It's a bit like a bungie jump. You go down to where you need to be (the element) but go immediately back to where you came from (the root element).

Share:
10,129
kskaradzinski
Author by

kskaradzinski

Updated on June 04, 2022

Comments

  • kskaradzinski
    kskaradzinski almost 2 years

    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.

  • kskaradzinski
    kskaradzinski almost 13 years
    I want to get attributes but dont know how ?? and rest of values, which a get Nodes location = doc.query("//location[location_name='"+ locationName +"']/*"); location.get(7).getValue(); now
  • kskaradzinski
    kskaradzinski almost 13 years
    Ok but how to get selected node ??
  • kskaradzinski
    kskaradzinski almost 13 years
    where have U been for so long :) +50 4 U