2

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
kskaradzinski
  • 4,954
  • 10
  • 48
  • 70

3 Answers3

4

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>
orangepips
  • 9,891
  • 6
  • 33
  • 57
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).

extraneon
  • 23,575
  • 2
  • 47
  • 51
Harry Lime
  • 29,476
  • 4
  • 31
  • 37
0

It's not clear (at least for me) what actually has to be done. From your query you should get list of nodes matching the given criteria. You will get NodeList and then you can iterate over this NodeList and get content of each node with getNodeValue for example.

jdevelop
  • 12,176
  • 10
  • 56
  • 112